perm filename WEAVEX.WEB[WEB,ALS]1 blob sn#623637 filedate 1981-11-13 generic text, type C, neo UTF8
COMMENT ⊗   VALID 00023 PAGES
C REC  PAGE   DESCRIPTION
C00001 00001
C00003 00002	% Here is TEX material that gets inserted after \input webhdr
C00006 00003	@* Introduction.
C00017 00004	@* Input and output.
C00024 00005	@* Reporting errors to the user.
C00030 00006	@* Data structures.
C00045 00007	@* Searching for identifiers.
C00051 00008	@* Initializing the table of reserved words.
C00061 00009	@* Searching for module names.
C00067 00010	@* Lexical scanning.
C00084 00011	@* Inputting the next token.
C00096 00012	@* Phase one processing.
C00107 00013	@* Low-level output routines.
C00117 00014	@* Routines that copy \TEX\ material.
C00124 00015	@* Parsing.
C00152 00016	@* Implementing the productions.
C00185 00017	@* Initializing the scraps.
C00200 00018	@* Output of tokens.
C00219 00019	@* Phase two processing.
C00234 00020	@* Phase three processing.
C00245 00021	@* Debugging.
C00253 00022	@* The main program.
C00255 00023	@* Index.
C00259 ENDMK
C⊗;
% Here is TEX material that gets inserted after \input webhdr
\def\hang{\hangindent 3em\ \unskip\!}
\chcode'27=13 \def↔{\ifmmode{\mathrel{\char'444}}\else{\penalty999\ } }
	% make ↔ tie two words together except in math mode
\def\TEX{\hbox{T\hskip-.1667em\lower.424ex\hbox{E}\hskip-.125em X}}
\font b=cmr9 \def\mc{\:b} % medium caps for names like PASCAL
\def\PASCAL{{\mc PAS}\-{\mc CAL}}
\def\pb{$\.|\ldotsm\.|$} % pascal brackets (|...|)
\def\v{\.{\char'174}} % vertical (|) in typewriter font

\font D=cmtt at 15truept % font used in the title line below (only)
\font E=cmr7 at 14truept % font used in the title line below (only)
\topspace 0pt
\vfill
\ctrline{\:E The {\:D WEAVE} processor}
\vskip 15pt
\ctrline{(preliminary version, November 1981)}
\vfill
\ctrline{\baselineskip9pt\hbox par 5in{\:bThis copy of the program is
	being distributed to interested ``guinea pigs'' before it has
	been thoroughly tested, in order to get extra help in the testing
	process. It is expected that changes will be made frequently
	while \TEX82 is being developed in the next months. Several
	comments in this documentation imply that the program has
	already been applied successfully to \TEX; such remarks are
	merely 	wishful thinking at this point, but they will be true
	when the final version is completed.}}
\mark{1}\eject
@* Introduction.
This program converts a \.{WEB} file to a \TEX\ file. It was written
by D. E. Knuth in October, 1981; a somewhat similar {\mc SAIL} program had
been developed in March, 1979. 

The code uses a few features of the local \PASCAL\ compiler that may need
to be changed in other installations:

\yskip\item{1)} Case statements have a default.
\item{2)} Input-output is done with ascii characters in a way that allows
end-of-page marks to be distinguished from end-of-line marks.

\yskip\noindent
These features are also present in the \PASCAL\ version of \TEX, where they
are used in a similar (but more complex) way. System-dependent portions
of \.{WEAVE} can be identified by looking at the entries for `system
dependencies' in the index below.
@!@↑system dependencies@>

@ The program begins with a fairly normal header, made up of pieces that
@↑system dependencies@>
will mostly be filled in later. The \.{WEB} input comes from file |input|,
the \TEX\ output goes to file |output|, and error messages go to the
terminal (|tty|). 

If it is necessary to abort the job because of a fatal error, the program
calls the `|quit|' procedure, which goes to the label |end_of_WEAVE|.

@d end_of_WEAVE = 9999 {go here to wrap it up}

@p @<Compiler directives@>@/
program WEAVE(input,output,tty);
label end_of_WEAVE; {go here to finish}
const @<Constants in the outer block@>@/
type @<Types in the outer block@>@/
var @<Globals in the outer block@>@/
@<Error handling procedures@>@/
procedure initialize;
	var @<Local variables for initialization@>@/
	begin @<Set initial values@>@/
	end;

@ Some of this code is optional for use when debugging only; such material
is enclosed between the delimiters |debug| and $|gubed|$. 
Other parts, delimited by |stat| and $|tats|$,
are optionally included if statistics about \.{WEAVE}'s memory
usage are desired. Another small section of the program
@↑system dependencies@>
is used to skip the `directory pages' in files produced with the {\mc E} editor
at Stanford; that code is delimited by |stanford| and $|drofnats|$.

@d debug==@{ {change this to `$\\{debug}\eqv\null$' when debugging}
@d gubed==@} {change this to `$\\{gubed}\eqv\null$' when debugging}
@f debug==begin
@f gubed==end
@#
@d stat== {change this to `$\\{stat}\eqv\null$' when gathering usage statistics}
@d tats== {change this to `$\\{tats}\eqv\null$' when gathering usage statistics}
@f stat==begin
@f tats==end
@#
@d stanford== {change this to `$\\{stanford}\eqv\.{@@\{}$' when not
	using {\mc E} files}
@d drofnats== {change this to `$\\{drofnats}\eqv\.{@@\}}$' when not
	using {\mc E} files}
@f stanford==begin
@f drofnats==end

@ The \PASCAL\ compiler used to develop this system has ``compiler
directives'' that can appear in comments whose first character is a dollar sign.
In production versions of \.{WEAVE} these directives tell the compiler that
@↑system dependencies@>
it is safe to avoid range checks and to leave out the extra code it inserts
for the \PASCAL\ debugger's benefit, although interrupts will occur if
there is arithmetic overflow.

@<Compiler directives@>=
@{@&$C-,A+,D-@} {no range check, catch arithmetic overflow, no debug overhead}
debug @{@&$C+,D+@}@+ gubed {but turn everything on when debugging}

@ Labels are given symbolic names by the following definitions. We insert
the label `|exit|:' just before the \&{end} of a procedure in which we have
used the `\&{return}' statement defined below;
the label `|restart|' is occasionally used at the very beginning of a
procedure; and the label `|reswitch|' is occasionally used just prior to
a \&{case} statement in which some cases change the conditions and we wish to
branch to the newly applicable case.
Loops that are set up with the \&{loop} construction defined below are
commonly exited by going to `|done|' or to `|found|' or to `|not_found|',
and they are sometimes repeated by going to `|continue|'.

@d exit=10 {go here to leave a procedure}
@d restart=20 {go here to start a procedure again}
@d reswitch=21 {go here to start a case statement again}
@d continue=22 {go here to resume a loop}
@d done=30 {go here to exit a loop}
@d found=31 {go here when you've found it}
@d not_found=32 {go here when you've found something else}

@ Here are some macros for common programming idioms and for the default
case statement.
@↑system dependencies@>

@d incr(#) == #←#+1 {increase a variable by unity}
@d decr(#) == #←#-1 {decrease a variable by unity}
@d loop == @+ while true do@+ {repeat over and over until a |goto| happens}
@d do_nothing == {empty statement}
@d return == goto exit {terminate a procedure call}
@d othercases == others: {default for cases not listed explicitly}
@d endcases == @+end {follows the default case}
@f othercases == else
@f endcases == end
@f return == nil
@f loop == xclause

@ The following parameters are set big enough to handle \TEX, so they
should be sufficient for most applications of \.{WEAVE}.

@<Constants...@>=
@!max_bytes=20000; {number of bytes in identifiers, index entries, and
	module names; must be less than 65536}
@!max_names=2000; {number of identifiers, index entries, and module names;
	must be less than 10240}
@!hash_size=353; {should be prime}
@!buf_size=100; {maximum length of input line}
@!longest_name=300; {module names shouldn't be longer than this}
@!long_buf_size=400; {|buf_size+longest_name|}
@!line_length=80; {lines of \TEX\ output have at most this many characters,
	should be less than 256}
@!max_refs=12000; {number of cross references; must be less than 65536}
@!max_toks=20000; {number of symbols in \PASCAL\ texts being parsed;
	must be less than 65536}
@!max_texts=2000; {number of phrases in \PASCAL\ texts being parsed;
	must be less than 10240}
@!max_scraps=1000; {number of tokens in \PASCAL\ texts being parsed}
@!stack_size=200; {number of simultaneous output levels}

@ The numbers in the following definitions are ``ascii codes'' for special
characters that aren't standard in ascii. The codes for |left_arrow| and
|not_equal| tend to vary at different sites, but the other codes have
the stated meaning at Stanford, MIT, Carnegie, USC, etc.
@↑system dependencies@>

@d and_sign=@'4
@d not_sign=@'5
@d set_element_sign=@'6
@d or_sign=@'37
@d equivalence_sign=@'36
@d greater_or_equal="≥" {normally |@'35|}
@d less_or_equal="≤" {normally |@'34|}
@d not_equal="≠" {|@'33| at Stanford, Carnegie, etc.; |@'32| at MIT}
@d left_arrow="←" {|@'137| at Stanford, Carnegie, etc.; |@'30| at MIT}
@* Input and output.
The input conventions of this program are intended to be very much like those
of \TEX\ (except, of course, that they are much simpler, because much less
needs to be done). Furthermore they are identical to those of \.{TANGLE}.
Therefore people who need to make modifications to all three systems
@↑system dependencies@>
should be able to do so without too many headaches.

However, we use the standard \PASCAL\ input/output procedures here wherever
possible, since \.{WEAVE} does not have to deal with files that are named
dynamically by the user, and since there is no input from the terminal.

@ Terminal output is done by writing on file |tty|:
@↑system dependencies@>

@d print(#)==write(tty,#) {`|print|' means write on the terminal}
@d print_ln(#)==write_ln(tty,#) {`|print|' and then start new line}
@d print_nl(#)==  {print information starting on a new line}
	begin write_ln(tty); print(#); 	end
@d ex_print_nl(#)==  write_ln(tty); print(#);

@ The following code re-opens the |input| file in a mode that (a)↔allows us
to see end-of-line characters, and (b)↔does not get the first character;
@↑system dependencies@>
the first |read_ln| does the first |get|. As we will see below, \.{WEAVE}
reads through the entire input file twice. The procedure returns |true| if
the file could not be opened.

@p function open_input:boolean; {prepare for ascii input on the |input| file}
begin reset(input,'','/E/I/O');
open_input←eof(input);
end;

@ The external text files we work with are of type |char|, which is the full
7-bit ascii code on our local \PASCAL.
@↑system dependencies@>
Internal calculations of \.{WEAVE} are, however, done entirely with the
type |ascii_code|, which is a subrange of the integers. The |ord| and |chr|
functions of \PASCAL\ are used to convert to and from |ascii_code| numbers.

@<Types...@>=
@!ascii_code = 0..127; {seven-bit numbers}

@ Input goes into an array called |buffer|.

@<Globals...@>=@!buffer: array[0..long_buf_size] of ascii_code;

@ The following procedure gets one line of input, according to the conventions
of \TEX, namely: If the |input| file has been entirely read, |input_ln| returns
|false| and does nothing else. Otherwise if the next item in the file is an
end-of-page mark, the procedure sets |buffer[0]←form_feed|, |limit←0|, and
returns |true|. Otherwise |ascii_code| numbers representing the next line
of the file are input into |buffer[0]|, |buffer[1]|, $\ldotss$, 
|buffer[limit-1]|; the global variable |limit| is set to the length of the
@↑system dependencies@>
line; |buffer[limit]| is set to an ascii |carriage_return|; and the
procedure returns |true|.

@d carriage_return=@'15 {ascii code (control-M) used at end of line}
@d form_feed=@'14	{ascii code (control-L) used at end of page}
@d tab_mark=@'11	{ascii code (control-I) used as tab-skip}

@p function input_ln:boolean; {inputs the next line or returns |false|}
begin read_ln; {|get| the first character of the line}
if eof(input) then input_ln←false
else	begin limit←0; buffer[0]←ord(input↑);
	if buffer[0]≠form_feed then {not end of page}
		while buffer[limit]≠carriage_return do
			if limit=buf_size-1 then {keep |buffer[buf_size]| empty}
				begin buffer[limit]←carriage_return;
				ex_print_nl('! Input line too long'); error;
				end
			else	begin incr(limit); get(input);
				if eof(input) then buffer[limit]←carriage_return
				else buffer[limit]←ord(input↑);
				end;
	input_ln←true;
	end;
end;
@* Reporting errors to the user.
The \.{WEAVE} processor operates in three phases: first it inputs the source
file and stores cross-reference data, then it inputs the source once again and
produces the \TEX\ output file, and finally it sorts and outputs the index.

The global variable |phase_one| tells whether we are in Phase I or not.

@<Globals...@>=
phase_one: boolean; {|true| in Phase I, |false| in Phase II}

@ If an error is detected while we are debugging,
we usually want to look at the contents of memory.
A special procedure will be declared later for this purpose.

@<Error handling...@>=
debug@+ procedure debug_help; forward;@+gubed

@ The command `|err_print('! Error message')|' will report a syntax error to
the user, by printing the error message at the beginning of a new line and
then giving an indication of where the error was spotted in the source file.
Note that no period follows the error message, since the error routine will
fill this in automatically.

The actual error indications are provided by a procedure called |error|.
However, error messages are not actually reported during phase one,
since errors detected on the first pass will be detected again
during the second.

@d err_print(#)==
	begin if ¬phase_one then
		begin ex_print_nl(#); error;
		end;
	end

@d ex_err_print(#)== if ¬phase_one then
		begin ex_print_nl(#); error; end

@<Error handling...@>=
procedure error; {prints `\..' and location of error message}
var@!k,@!l: 0..long_buf_size; {indices into |buffer|}
begin @<Print error location based on input buffer@>;
debug debug_skipped←debug_cycle;debug_help;@+gubed
end;

@ The error locations can be indicated by using the global variables
|loc|, |page|, and |line|, which tell respectively the first unlooked-at
position in |buffer|, the current page number, and the current line number.

@<Print error location based on input buffer@>=
begin print_ln('. (p.', page:0, ',l.', line:0, ')');
if loc≥limit then l←limit else l←loc;
for k←1 to l do
	if buffer[k-1]=tab_mark then print(' ')
	else print(chr(buffer[k-1])); {print the characters already read}
print_ln('');
for k←1 to l do print(' '); {space out the next line}
for k←l+1 to limit do print(chr(buffer[k-1])); {print the part not yet read}
print(' '); {this space separates the message from future page numbers}
end

@ The |quit| procedure just cuts across all active procedure levels
and jumps out of the program. This is the only non-local \&{goto} statement
in \.{WEAVE}. It is used when no recovery from a particular error has
been provided.

@d fatal_error(#)==begin ex_print_nl(#); error; quit;
	end

@<Error handling...@>=
procedure quit;
begin goto end_of_WEAVE;
end;

@ Sometimes the program's behavior is far different from what it should be,
and \.{WEAVE} prints an error message that is really for the \.{WEAVE}
maintenance person, not the user. In such cases the program says
|confusion('indication of where we are')|.

@d confusion(#)==fatal_error('! This can''t happen (',#,')')

@ An overflow stop occurs if \.{WEAVE}'s tables aren't large enough.

@d overflow(#)==fatal_error('! Sorry, ',#,' capacity exceeded')
@* Data structures.
During the first phase of its processing, \.{WEAVE} puts identifier names,
index entries, and module names into the large |byte_mem| array, which is
packed with seven-bit integers. Allocation is sequential, since names are
never deleted.

An auxiliary array |byte_start| is used as a directory for |byte_mem|,
and the |link|, |ilk|, and |xref| arrays give further information about names.
These auxiliary arrays consist of sixteen-bit items.

@<Types...@>=
@!eight_bits=0..255; {unsigned one-byte quantity}
@!sixteen_bits=0..65535; {unsigned two-byte quantity}

@ @<Globals...@>=
@!byte_mem: packed array [0..max_bytes] of ascii_code; {characters of names}
@!byte_start: array [0..max_names] of sixteen_bits; {directory into |byte_mem|}
@!link: array [0..max_names] of sixteen_bits; {hash table or tree links}
@!ilk: array [0..max_names] of sixteen_bits; {type codes or tree links}
@!xref: array [0..max_names] of sixteen_bits; {heads of cross-reference lists}

@ The names of identifiers are found by computing a hash address |h| and
then looking at strings of bytes signified by |hash[h]|, |link[hash[h]]|,
|link[link[hash[h]]]|, $\ldotss$, until either finding the desired name
or encountering a zero.

A `|name_pointer|' variable, which signifies a name, is an index into
|byte_start|. The actual sequence of characters in the name pointed to by
$p$ appears in positions |byte_start[p]| to |byte_start[p+1]-1|, inclusive,
in |byte_mem|. The pointer 0 is used for undefined module names; we don't
want to use it for the names of identifiers, since 0 stands for a null
pointer in a linked list.

We usually have |byte_start[name_ptr]=byte_ptr|, since this identifies the
end of the most recently created name, which is pointed to by |(name_ptr-1)|.

@d length(#)==byte_start[#+1]-byte_start[#] {the length of a name}

@<Types...@>=
@!name_pointer=0..max_names; {identifies a name}

@ @<Global...@>=
@!name_ptr:name_pointer; {first unused position in |byte_start|}
@!byte_ptr:0..max_bytes; {first unused position in |byte_mem|}

@ @<Set init...@>=
name_ptr←1; byte_ptr←1; byte_start[0]←1; byte_start[1]←1; 

@ Several types of identifiers are distinguished by their |ilk|:

\yskip\hang |normal| identifiers are part of the \PASCAL\ program and will
appear in italic type.

\yskip\hang |roman| identifiers are index entries that appear after \.{@@\↑}
in the \.{WEB} file.

\yskip\hang |typewriter| identifiers are index entries that appear after
\.{@@.} in the \.{WEB} file.

\yskip\hang |array_like|, |begin_like|, $\ldotss$, |var_like| identifiers
are \PASCAL\ reserved words whose |ilk| explains how they are to be treated
when \PASCAL\ code is being formatted.

\yskip\hang Finally, if $c$ is an ascii_code, an |ilk| equal to |char_like+c|
denotes a reserved word that will be converted to character $c$.

@d normal=0 {ordinary identifiers have |normal| ilk}
@d roman=1 {normal index entries have |roman| ilk}
@d typewriter=2 {`typewriter type' entries have |typewriter| ilk}
@d reserved(#)==ilk[#]>typewriter {tells if a name is a reserved word}
@d array_like=3 {\&{array}, \&{file}, \&{set}}
@d begin_like=4 {\&{begin}}
@d case_like=5 {\&{case}}
@d const_like=6 {\&{const}, \&{label}, \&{type}}
@d div_like=7 {\&{div}, \&{mod}}
@d do_like=8 {\&{do}, \&{of}, \&{then}}
@d else_like=9 {\&{else}}
@d end_like=10 {\&{end}}
@d for_like=11 {\&{for}, \&{while}, \&{with}}
@d goto_like=12 {\&{goto}, \&{packed}}
@d if_like=13 {\&{if}}
@d in_like=14 {\&{in}}
@d nil_like=15 {\&{nil}}
@d proc_like=16 {\&{function}, \&{procedure}, \&{program}}
@d record_like=17 {\&{record}}
@d repeat_like=18 {\&{repeat}}
@d to_like=19 {\&{downto}, \&{to}}
@d until_like=20 {\&{until}}
@d var_like=21 {\&{var}}
@d loop_like=22 {\&{loop}, \&{xclause}}
@d char_like=23 {\&{and}, \&{or}, \&{not}, \&{in}}

@ The names of modules are stored in |byte_mem| together
with the identifier names, but a hash table is not used for them because
\.{WEAVE} needs to be able to recognize a module name when given a prefix of
that name. A conventional binary seach tree is used to retrieve module names,
with fields called |llink| and |rlink| in place of |link| and |ilk|. The
root of this tree is |rlink[0]|.

@d llink==link {left link in binary search tree for module names}
@d rlink==ilk {right link in binary search tree for module names}

@<Set init...@>=
rlink[0]←0; {the binary search tree starts out with nothing in it}

@ Here is a little procedure that prints the text of a given name on the
user's terminal.

@p procedure print_id(p:name_pointer); {print identifier or module name}
var k:0..max_bytes; {index into |byte_mem|}
begin if p≥name_ptr then print('IMPOSSIBLE')
else for k←byte_start[p] to byte_start[p+1]-1 do print(chr(byte_mem[k]));
end;

@ The other large memory area in \.{WEAVE} keeps the cross-reference data.
All uses of the name $p$ are recorded in a linked list beginning at
|xref[p]|, which points into the |xmem| array. Entries in |xmem| consist
of two sixteen-bit items per word, called the |num| and |xlink| fields.
If $x$ is an index into |xmem|, reached from name $p$, the value of |num(x)|
is either a module number where $p$ is used, or it is |def_flag| plus a
module number where $p$ is defined; and |xlink(x)| points to the next such
cross reference for $p$, if any. This list of cross references is in
decreasing order by module number. The current number of cross references
is |xref_ptr|, and the current module number is |module_count|.

The global variable |xref_switch| is set either to |def_flag| or to zero,
depending on whether the next cross reference to an identifier is to be
underlined or not in the index. This switch is set to |def_flag| when
\.{@@!} or \.{@@d} or \.{@@f} is scanned, and it is cleared to zero when
the next identifier or index entry cross-reference has been made. Similarly,
the global variable |mod_xref_switch| is either |def_flag| or zero, depending
on whether a module name is being defined or used.

@d num(#)==xmem[#].num_field
@d xlink(#)==xmem[#].xlink_field
@d def_flag=10240

@<Globals...@>=
@!xmem:array[0..max_refs] of packed record@/
	@!num_field: sixteen_bits; {module number plus zero or |def_flag|}
	@!xlink_field: sixteen_bits; {pointer to the previous cross reference}
	end;
@!xref_ptr:0..max_refs; {the largest occupied position in |xmem|}
@!module_count:0..def_flag-1; {the current module number}
@!xref_switch,@!mod_xref_switch:0..def_flag; {either zero or |def_flag|}

@ @<Set init...@>=xref_ptr←0; xref_switch←0; mod_xref_switch←0; num(0)←0;

@ A new cross reference for an identifier is formed by calling |new_xref|,
which discards duplicate entries and ignores non-underlined references
to one-letter identifiers or \PASCAL's reserved words.

@d append_xref(#)==if xref_ptr=max_refs then overflow('cross reference')
	else	begin incr(xref_ptr); num(xref_ptr)←#;
		end

@p procedure new_xref(p:name_pointer);
label exit;
var q:0..max_refs; {pointer to previous cross-reference}
@!m,@!n: sixteen_bits; {new and previous cross-reference value}
begin if ((reserved(p))∨(byte_start[p]+1=byte_start[p+1]))∧(xref_switch=0) then
	return;
m←module_count+xref_switch; xref_switch←0; q←xref[p];
if q>0 then
	begin n←num(q);
	if (n=m)∨(n=m+def_flag) then return
	else if m=n+def_flag then
		begin num(q)←m; return;
		end;
	end;
append_xref(m); xlink(xref_ptr)←q; xref[p]←xref_ptr;
exit: end;

@ The cross reference lists for module names are slightly different. Suppose
that a module name is defined in modules $m↓1$, $\ldotss$, $m↓k$ and used in
modules $n↓1$, $\ldotss$, $n↓l$. Then its list will contain $m↓1+|def_flag|$,
$m↓k+|def_flag|$, $\ldotss$, $m↓2+|def_flag|$, $n↓l$, $\ldotss$, $n↓1$, in
this order.

@p procedure new_mod_xref(p:name_pointer);
var q,@!r:0..max_refs; {pointers to previous cross-references}
begin q←xref[p]; r←0;
if q>0 then
	begin if mod_xref_switch=0 then while num(q)≥def_flag do
		begin r←q; q←xlink(q);
		end
	else if num(q)≥def_flag then
		begin r←q; q←xlink(q);
		end;
	end;
append_xref(module_count+mod_xref_switch); xlink(xref_ptr)←q;
mod_xref_switch←0;
if r=0 then xref[p]←xref_ptr
else xlink(r)←xref_ptr;
end;

@ A third large area of memory is used for sixteen-bit `tokens', which appear
in short lists similar to the strings of characters in |byte_mem|. Token lists
are used to contain the result of \PASCAL\ code translated into \TEX\ form;
further details about them will be explained later. A |text_pointer| variable
is an index into |tok_start|.

@<Types...@>=
@!text_pointer=0..max_texts; {identifies a token list}

@ The first position of |tok_mem|
that is unoccupied by replacement text is called |tok_ptr|, and the first
unused location of |tok_start| is called |text_ptr|.
We usually have |tok_start[text_ptr]=tok_ptr|, for the same reason that
|byte_start[name_ptr]| is usually equal to |byte_ptr|.

@<Glob...@>=
@!tok_mem: packed array [0..max_toks] of sixteen_bits; {tokens}
@!tok_start: array [text_pointer] of sixteen_bits; {directory into |tok_mem|}
@!text_ptr:text_pointer; {first unused position in |tok_start|}
@!tok_ptr:0..max_toks; {first unused position in |tok_mem|}
stat@!max_tok_ptr,@!max_txt_ptr:0..max_toks; {largest values occurring}
tats

@ @<Set init...@>=
tok_ptr←1; text_ptr←1; tok_start[0]←1; tok_start[1]←1;
stat max_tok_ptr←1; max_txt_ptr←1;
tats
@* Searching for identifiers.
The hash table described above is updated by the |id_lookup| procedure,
which finds a given identifier and returns a pointer to its index in
|byte_start|. The identifier is supposed to match character by character
and it is also supposed to have a given |ilk| code; the same name may be
present more than once if it is supposed to appear in the index with
different typesetting conventions.
If the identifier was not already present, it is inserted into the table.

Because of the way \.{WEAVE}'s scanning mechanism works, it is most convenient
to let |id_lookup| search for an identifier that is present in the |buffer|
array. Two other global variables specify its position in the buffer: the
first character is |buffer[id_first]|, and the last is |buffer[id_loc-1]|.

@<Glob...@>=
@!id_first:0..long_buf_size; {where the current identifier begins in the buffer}
@!id_loc:0..long_buf_size; {just after the current identifier in the buffer}
@#
@!hash:array [0..hash_size] of sixteen_bits; {heads of hash lists}

@ Initially all the hash lists are empty.

@<Local variables for init...@>=
@!h:0..hash_size; {index into hash-head array}

@ @<Set init...@>=
for h←0 to hash_size-1 do hash[h]←0;

@ Here now is the main procedure for finding identifiers (and index entries).
The parameter $t$ is set to the desired |ilk| code. The identifier must either
have |ilk=t|, or we must have |t=normal| and the identifier must be a
reserved word.

@p function id_lookup(t:eight_bits):name_pointer; {finds current identifier}
label found, not_found;
var i:0..long_buf_size; {index into |buffer|}
@!h:0..hash_size; {hash code}
@!k:0..max_bytes; {index into |byte_mem|}
@!l:0..long_buf_size; {length of the given identifier}
@!p,@!q:name_pointer; {where the identifier is being sought}
begin l←id_loc-id_first; {compute the length}
@<Compute the hash code $h$@>;
@<Compute the name location $p$@>;
if p=name_ptr then @<Enter a new name into the table at position $p$@>;
id_lookup←p;
end;

@ A simple hash code is used: If the sequence of
ascii_codes is $c↓1c↓2\ldotsm c↓m$, its hash value will be
$$(2↑{n-1}c↓1+2↑{n-2}c↓2+\cdots+c↓n)\,\modop\,|hash_size|.$$

@<Compute the hash...@>=
h←buffer[id_first]; i←id_first+1;
while i<id_loc do
	begin h←(h+h+buffer[i]) mod hash_size; incr(i);
	end

@ If the identifier is new, it will be placed in position |p=name_ptr|, 
otherwise $p$ will point to its existing location.

@<Compute the name location...@>=
p←hash[h];
while p≠0 do
	begin if (length(p)=l)∧((ilk[p]=t)∨((t=normal)∧(reserved(p)))) then
	    @<Compare name $p$ with current identifier, |goto found| if equal@>;
	p←link[p];
	end;
p←name_ptr; {the current identifier is new}
link[p]←hash[h]; hash[h]←p; {insert $p$ at beginning of hash list}
found:

@ @<Compare name $p$...@>=
begin i←id_first; k←byte_start[p];
while (i<id_loc)∧(buffer[i]=byte_mem[k]) do
	begin incr(i); incr(k);
	end;
if i=id_loc then goto found; {all characters agree}
end

@ The following routine could make good use of a generalized |pack| procedure
that puts items into just part of a packed array instead of the whole thing.

@<Enter a new name...@>=
begin if byte_ptr+l>max_bytes then overflow('byte memory');
if name_ptr=max_names then overflow('name');
i←id_first; k←byte_ptr; {get ready to move the identifier into |byte_mem|}
while i<id_loc do
	begin byte_mem[k]←buffer[i]; incr(k); incr(i);
	end;
byte_ptr←k; incr(name_ptr); byte_start[name_ptr]←k;
ilk[p]←t; xref[p]←0;
end
@* Initializing the table of reserved words.
We have to get \PASCAL's reserved words into the hash table, and the
simplest way to do this is to insert them every time \.{WEAVE} is run.
A few macros permit us to do the initialization with a compact program.

@d sid9(#)==buffer[9]←#;cur_name←id_lookup
@d sid8(#)==buffer[8]←#;sid9
@d sid7(#)==buffer[7]←#;sid8
@d sid6(#)==buffer[6]←#;sid7
@d sid5(#)==buffer[5]←#;sid6
@d sid4(#)==buffer[4]←#;sid5
@d sid3(#)==buffer[3]←#;sid4
@d sid2(#)==buffer[2]←#;sid3
@d sid1(#)==buffer[1]←#;sid2
@d id2==id_first←8; sid8
@d id3==id_first←7; sid7
@d id4==id_first←6; sid6
@d id5==id_first←5; sid5
@d id6==id_first←4; sid4
@d id7==id_first←3; sid3
@d id8==id_first←2; sid2
@d id9==id_first←1; sid1

@<Globals...@>=
@!cur_name:name_pointer; {points to the identifier just inserted}

@ The intended use of the macros above might not be immediately obvious,
but the riddle is answered by the following:

@<Store all the reserved words@>=
id_loc←10;@/
id3("a")("n")("d")(char_like+and_sign);@/
id5("a")("r")("r")("a")("y")(array_like);@/
id5("b")("e")("g")("i")("n")(begin_like);@/
id4("c")("a")("s")("e")(case_like);@/
id5("c")("o")("n")("s")("t")(const_like);@/
id3("d")("i")("v")(div_like);@/
id2("d")("o")(do_like);@/
id6("d")("o")("w")("n")("t")("o")(to_like);@/
id4("e")("l")("s")("e")(else_like);@/
id3("e")("n")("d")(end_like);@/
id4("f")("i")("l")("e")(array_like);@/
id3("f")("o")("r")(for_like);@/
id8("f")("u")("n")("c")("t")("i")("o")("n")(proc_like);@/
id4("g")("o")("t")("o")(goto_like);@/
id2("i")("f")(if_like);@/
id2("i")("n")(char_like+set_element_sign);@/
id5("l")("a")("b")("e")("l")(const_like);@/
id3("m")("o")("d")(div_like);@/
id3("n")("i")("l")(nil_like);@/
id3("n")("o")("t")(char_like+not_sign);@/
id2("o")("f")(do_like);@/
id2("o")("r")(char_like+or_sign);@/
id6("p")("a")("c")("k")("e")("d")(goto_like);@/
id9("p")("r")("o")("c")("e")("d")("u")("r")("e")(proc_like);@/
id7("p")("r")("o")("g")("r")("a")("m")(proc_like);@/
id6("r")("e")("c")("o")("r")("d")(record_like);@/
id6("r")("e")("p")("e")("a")("t")(repeat_like);@/
id3("s")("e")("t")(array_like);@/
id4("t")("h")("e")("n")(do_like);@/
id2("t")("o")(to_like);@/
id4("t")("y")("p")("e")(const_like);@/
id5("u")("n")("t")("i")("l")(until_like);@/
id3("v")("a")("r")(var_like);@/
id5("w")("h")("i")("l")("e")(for_like);@/
id4("w")("i")("t")("h")(for_like);@/
id7("x")("c")("l")("a")("u")("s")("e")(loop_like);@/
@* Searching for module names.
The |mod_lookup| procedure finds the module name |module[1..l]| in the
search tree, after inserting it if necessary, and returns a pointer to
where it was found.

@<Glob...@>=
@!module:array [0..longest_name] of ascii_code; {name being sought for}

@ According to the rules of \.{WEB}, no module name
should be a proper prefix of another, so a ``clean'' comparison should
occur between any two names. The result of |mod_lookup| is↔0 if this
prefix condition is violated. An error message is printed when such violations
are detected during phase two of \.{WEAVE}.

@p function mod_lookup(l:sixteen_bits):name_pointer; {finds module name}
label found;
var c:(less,equal,greater,prefix,extension); {comparison between two names}
@!j:0..longest_name; {index into |module|}
@!k:0..max_bytes; {index into |byte_mem|}
@!p:name_pointer; {current node of the search tree}
@!q:name_pointer; {father of node $p$}
begin c←greater; q←0; p←rlink[0]; {|rlink[0]| is the root of the tree}
while p≠0 do
	begin @<Set $c$ to the result of comparing the given name to name $p$@>;
	q←p;
	if c=less then p←llink[q]
	else if c=greater then p←rlink[q]
	else goto found;
	end;
@<Enter new module name into the tree@>;
found: if c≠equal then
	begin ex_err_print('! Incompatible module names'); p←0;
	end;
mod_lookup←p;
end;

@ @<Enter new module name...@>=
if byte_ptr+l>max_bytes then overflow('byte memory');
if name_ptr=max_names then overflow('name');
p←name_ptr;
if c=less then llink[q]←p else rlink[q]←p;
llink[p]←0; rlink[p]←0; xref[p]←0; c←equal;
for j←1 to l do byte_mem[byte_ptr+j-1]←module[j];
byte_ptr←byte_ptr+l; incr(name_ptr); byte_start[name_ptr]←byte_ptr;

@ @<Set $c$...@>=
begin k←byte_start[p]; c←equal; j←1;
while (k<byte_start[p+1]) ∧ (j≤l) ∧ (module[j]=byte_mem[k]) do
	begin incr(k); incr(j);
	end;
if k=byte_start[p+1] then
	if j>l then c←equal
	else c←extension
else if j>l then c←prefix
else if module[j]<byte_mem[k] then c←less
else c←greater;
end

@ The |prefix_lookup| procedure is supposed to find exactly one module
name that has |module[1..l]| as a prefix. Actually the algorithm silently
accepts also the situation that some module name is a prefix of |module[1..l]|,
because the user who painstakingly typed in more than necessary probably
doesn't want to be told about the wasted effort.

Recall that error messages are not printed during phase one. It is possible
that the |prefix_lookup| procedure will fail on the first pass, because there
is no match, yet the second pass might detect no error if a matching module
name has occurred after the offending prefix. In such a case the cross-reference
information will be incorrect and \.{WEAVE} will report no error. However,
such a mistake will be detected by the \.{TANGLE} processor.

@p function prefix_lookup(l:sixteen_bits):name_pointer; {finds name extension}
label found;
var c:(less,equal,greater,prefix,extension); {comparison between two names}
@!count:0..max_names; {the number of hits}
@!j:0..longest_name; {index into |module|}
@!k:0..max_bytes; {index into |byte_mem|}
@!p:name_pointer; {current node of the search tree}
@!q:name_pointer; {another place to resume the search after one branch is done}
@!r:name_pointer; {extension found}
begin q←0; p←rlink[0]; count←0; r←0; {begin search at root of tree}
while p≠0 do
	begin @<Set $c$ to the result of comparing...@>;
	if c=less then p←llink[p]
	else if c=greater then p←rlink[p]
	else	begin r←p; incr(count); q←rlink[p]; p←llink[p];
		end;
	if p=0 then
		begin p←q; q←0;
		end;
	end;
if count≠1 then
	if count=0 then err_print('! Name does not match')
	else err_print('! Ambiguous prefix');
prefix_lookup←r; {the result will be 0 if there was no match}
end;
@* Lexical scanning.
Let us now consider the subroutines that read the \.{WEB} source file
and break it into meaningful units. There are four such procedures:
One simply skips to the next `\.{@@\ }' or `\.{@@*}' that begins a
module; another passes over the \TEX\ text at the beginning of a
module; the third passes over the \TEX\ text in a \PASCAL\ comment;
and the last, which is the most interesting, gets the next token of
a \PASCAL\ text.

@ But first we need to consider the low-level routine that takes care of
updating page and line numbers for error messages and progress reports.
This routine also makes sure that the input ends with an end-of-page signal.
The conventions of \TEX's input routine are used in simplified form: When
|line=0|, it is time to read a new page. After a line has been input, either
|buffer[limit]| is a |carriage_return|, on a normal line, or we have
|limit=0| and |buffer[0]=form_feed|, in which case this is the line that
ends a page. The value of |limit| is always strictly less than |long_buf_size-1|,
and the |buffer| array has subscripts extending to |long_buf_size|,
so it is possible to refer to |buffer[limit+2]| without overstepping the
bounds of the array. (The end of the buffer is used during phase two to
contain module names as we convert them to \TEX\ form.)

@<Globals...@>=
@!page:sixteen_bits; {the number of the page currently being read}
@!line:sixteen_bits; {the number of the current line on the current page}
@!limit:0..long_buf_size; {the last character position occupied in the buffer}
@!loc:0..long_buf_size; {the next character position to be read from the buffer}
@!input_has_ended: boolean; {if |true|, there is no more input}

@ The |reset_input| procedure, which gets \.{WEAVE} ready to read the user's
\.{WEB} input, is used at the beginning of phases one and two.

@p procedure reset_input;
begin if open_input then
	begin ex_print_nl('! Couldn''t open the input file.'); quit;
	end;
page←0; line←0; limit←0; loc←1; buffer[0]←" ";
input_has_ended←false;
end;

@ The |get_line| procedure is called when |loc>limit|; it puts the next
line of input into the buffer and updates the other variables appropriately.
A carriage return at the end of a line is changed to a space.

@p procedure get_line; {inputs the next line}
begin if buffer[0]=form_feed then line←0;
if input_ln then {not end of file}
	begin if line=0 then {first line of page}
		begin incr(page); print(page:0,' '); {print progress report}
		@<Special check for file directory page@>;
		end;
	if buffer[limit]=carriage_return then buffer[limit]←" ";
	end
else if buffer[0]≠form_feed then {insert page mark at end of file}
	begin limit←0; buffer[0]←form_feed;
	end
else input_has_ended←true; {note that page mark is still present}
incr(line); loc←0;
end;

@ The `{\mc E}' editor on Stanford's {\mc SAIL} computer, where the present version
of \.{WEAVE} was developed, makes up a special first page called the `file
directory' for the files it works with.
This first page is recognizable with sufficiently high
probability by the fact that its first line has length 29 and its first
and ninth characters are respectively `\.C' and `\.\⊗'. So the Stanford
version of \.{WEAVE} has special code to skip past all but the page mark
of such a first page:

@<Globals...@>=
stanford omit_page:boolean; {an extra input page has occurred}
drofnats

@ @<Set init...@>=
stanford omit_page←false;
drofnats

@ @<Special check for file directory page@>=
stanford if (page=1)∧(limit=29) then
	if (buffer[0]="C")∧(buffer[8]="⊗") then
		begin repeat if input_ln then do_nothing
			else	begin limit←0; buffer[0]←form_feed;
				end;
		until buffer[0]=form_feed;
		omit_page←true;
		end
drofnats

@ Control codes in \.{WEB}, which begin with `\.{@@}', are converted
into a numeric code designed to simplify \.{WEAVE}'s logic; for example,
larger numbers are given to the control codes that denote more significant
milestones, and the code of |new_module| should be the largest of
all. Some of these numeric control codes take the place of ascii
control codes that will not otherwise appear in the output of the
scanning routines.

@d ignore=0 {control code of no interest to \.{WEAVE}}
@d begin_comment=@'11 {ascii tab mark will not appear}
@d end_comment=@'12 {ascii line feed will not appear}
@d octal=@'14 {ascii form feed will not appear}
@d param=@'15 {ascii carriage return will not appear}
@d double_dot=@'40 {ascii space will not appear except in strings}
@d no_underline=@'175 {this code will be intercepted without confusion}
@d underline=@'176 {this code will be intercepted without confusion}
@d join=@'177 {ascii delete will not appear}
@d xref_roman=@'203 {control code for `\.{@@\↑}'}
@d xref_typewriter=@'204 {control code for `\.{@@.}'}
@d TEX_string=@'205 {control code for `\.{@@t}'}
@d thin_space=@'206 {control code for `\.{@@,}'}
@d line_break=@'207 {control code for `\.{@@/}'}
@d big_line_break=@'210 {control code for `\.{@@\#}'}
@d no_line_break=@'211 {control code for `\.{@@+}'}
@d pseudo_semi=@'212 {control code for `\.{@@;}'}
@d format=@'213 {control code for `\.{@@f}'}
@d definition=@'214 {control code for `\.{@@d}'}
@d begin_pascal=@'215 {control code for `\.{@@p}'}
@d module_name=@'216 {control code for `\.{@@<}'}
@d page_end=@'217 {control code for end-of-page}
@d new_module=@'220 {control code for `\.{@@\ }' and `\.{@@*}'}

@ Control codes are converted from ascii to \.{WEAVE}'s internal 
representation by the |control_code| routine.

@p function control_code(c:ascii_code):eight_bits; {convert $c$
	after \.{@@}}
begin case c of
"@@": control_code←"@@"; {`quoted' at sign}
"'":  control_code←octal; {precedes octal constant}
" ",tab_mark,"*": control_code←new_module; {beginning of a new module}
"D","d": control_code←definition; {macro definition}
"F","f": control_code←format; {format definition}
"{": control_code←begin_comment; {begin-comment delimiter}
"}": control_code←end_comment; {end-comment delimiter}
"P","p": control_code←begin_pascal; {\PASCAL\ text in unnamed module}
"&": control_code←join; {concatenate two tokens}
"<": control_code←module_name; {beginning of a module name}
">": begin ex_err_print('! Extra @@>'); control_code←ignore;
	end; {end of module name should not be discovered in this way}
"T","t": control_code←TEX_string; {\TEX\ box within \PASCAL}
"!": control_code←underline; {set definition flag}
"?": control_code←no_underline; {reset definition flag}
"↑": control_code←xref_roman; {index entry to be typeset normally}
".": control_code←xref_typewriter; {index entry to be in typewriter type}
",": control_code←thin_space; {puts extra space in \PASCAL\ format}
"/": control_code←line_break; {forces end-of-line in \PASCAL\ format}
"#": control_code←big_line_break; {forces end-of-line and some space besides}
"+": control_code←no_line_break; {cancels end-of-line down to single space}
";": control_code←pseudo_semi; {acts like a semicolon, but is invisible}
@t\4@>@<Special control codes allowed only when debugging@>;
othercases begin ex_err_print('! Unknown control code'); control_code←ignore;
	end
endcases;
end;

@ If \.{WEAVE} is compiled with debugging commands, one can write
\.{@@1} and \.{@@0} to turn tracing on and off. 

@<Special control codes...@>=
debug@t@>@/
"0": begin tracing←false; control_code←ignore;
	end;
"1": begin tracing←true; control_code←ignore;
	end;
gubed

@ The |skip_limbo| routine is used on the first pass to skip through
portions of the input that are not in any modules, i.e., that precede
the first module or that immediately follow the end of a page in the
file. After this procedure has been called, the value of
|input_has_ended| will tell whether or not a new module has
actually been found.

@p procedure skip_limbo; {skip to next module}
label exit;
var c:ascii_code; {character following \.{@@}}
begin loop if loc>limit then
		begin get_line;
		if buffer[0]=form_feed then if input_has_ended then return
			else loc←1;
		end
	else	begin buffer[limit+1]←"@@";
		while buffer[loc]≠"@@" do incr(loc);
		if loc≤limit then
			begin loc←loc+2; c←buffer[loc-1];
			if (c=" ")∨(c=tab_mark)∨(c="*") then return;
			end;
		end;
exit: end;

@ The |skip_TEX| routine is used on the first pass to skip through
the \TEX\ code at the beginning of a module. It returns the next
control code or `\v' or end-of-page found in the input.

@p function skip_TEX: eight_bits; {skip past pure \TEX\ code}
label done;
var c:eight_bits; {control code found}
begin loop begin if loc>limit then
		begin get_line;
		if buffer[0]=form_feed then
			begin loc←1; c←page_end; goto done;
			end;
		end;
	buffer[limit+1]←"@@";
	repeat c←buffer[loc]; incr(loc);
	if c="|" then goto done;
	until c="@@";
	if loc≤limit then
		begin c←control_code(buffer[loc]); incr(loc); goto done;
		end;
	end;
done:skip_TEX←c;
end;

@ The |skip_comment| routine is used on the first pass to skip
through \TEX\ code in \PASCAL\ comments. The |bal| parameter
tells how many left braces are assumed to have been scanned when
this routine is called, and the procedure returns a corresponding
value of |bal| at the point that scanning has stopped. Scanning
stops either at a `\v' that introduces \PASCAL\ text,
in which case the returned value is positive, or it stops at the
end of the comment, in which case the returned value is zero.
The scanning also stops in anomalous situations when the comment
doesn't end on the page or when it contains an illegal use
of \.{@@}. One should call |skip_comment(1)| when beginning
to scan a comment.

@p function skip_comment(bal:eight_bits):eight_bits; {skips \TEX\
	code in comments}
label done;
var c:ascii_code; {the current character}
begin loop begin if loc>limit then
		begin get_line;
		if buffer[0]=form_feed then
			begin loc←1; bal←0; goto done;
			end; {an error message will occur in phase two}
		end;
	c←buffer[loc]; incr(loc);
	if c="|" then goto done;
	@<Do special things when |c="@@", "\", "{", "}"|; |goto done| at end@>;
	end;
done: skip_comment←bal;
end;

@ @<Do special things when |c="@@"...@>=
if c="@@" then
	begin c←buffer[loc];
	if (c≠" ")∧(c≠tab_mark)∧(c≠"*") then incr(loc)
	else	begin decr(loc); bal←0; goto done;
		end {an error message will occur in phase two}
	end
else if (c="\")∧(buffer[loc]≠"@@") then incr(loc)
else if c="{" then incr(bal)
else if c="}" then
	begin decr(bal);
	if bal=0 then goto done;
	end
@* Inputting the next token.
As stated above, \.{WEAVE}'s most interesting lexical scanning routine is the
|get_next| function that inputs the next token of \PASCAL\ input. However,
|get_next| is not especially complicated.

The result of |get_next| is either an ascii code for some special character,
or it is a special code representing a pair of characters (e.g., `\.{:=}'
or `\.{..}'), or it is the numeric value computed by the |control_code|
procedure, or it is one of the following special codes:

\yskip\hang |exponent|: The `\.E' in a real constant.

\yskip\hang |identifier|: In this case the global variables |id_first| and
|id_loc| will have been set to the appropriate values needed by the
|id_lookup| routine.

\yskip\hang |string|: In this case the global variables |id_first| and |id_loc|
will have been set to the beginning and ending-plus-one locations in the buffer.
The string ends with the first reappearance of its initial delimiter; thus,
for example,
$$\.{\'This isn\'\'t a single string\'}$$
will be treated as two consecutive strings, the first being \.{\'This isn\'}.

\yskip\noindent Furthermore, some of the control codes cause |get_next| to
take additional actions:

\yskip\hang |xref_roman|, |xref_typewriter|, |TEX_string|: The values of
|id_first| and |id_loc| will be set so that the string in question appears
in |buffer[id_first..(id_loc-1)]|.

\yskip\hang |module_name|: In this case the global variable |cur_module| will
point to the |byte_start| entry for the module name that has just been scanned.

\yskip\noindent If |get_next| sees `\.{@@!}' or `\.{@@?}',
it sets |xref_switch| to |def_flag| or zero and goes on to the next token.

@d exponent=@'200 {\.E following a digit}
@d string=@'201 {\PASCAL\ string or \.{WEB} precomputed string}
@d identifier=@'202 {\PASCAL\ identifier or reserved word}

@<Globals...@>=
@!cur_module: name_pointer; {name of module just scanned}

@ As one might expect, |get_next| consists mostly of a big switch
that branches to the various special cases that can arise.

@d up_to(#)==#-24,#-23,#-22,#-21,#-20,#-19,#-18,#-17,#-16,#-15,#-14,
	#-13,#-12,#-11,#-10,#-9,#-8,#-7,#-6,#-5,#-4,#-3,#-2,#-1,#

@p function get_next:eight_bits; {produces the next input token}
label restart,done;
var c:eight_bits; {the current character}
@!d:eight_bits; {the next character}
@!j,@!k:0..longest_name; {indices into |module|}
begin restart: if loc>limit then get_line;
c←buffer[loc]; incr(loc);
case c of
"A",up_to("Z"),"a",up_to("z"): @<Get an identifier@>;
"'","""": @<Get a string@>;
"@@": @<Get control code and possible module name@>;
@t\4@>@<Compress two-symbol combinations like `\.{:=}'@>@;
" ",tab_mark: goto restart; {ignore spaces and tabs}
form_feed: c←page_end;
othercases do_nothing
endcases;
debug if trouble_shooting then debug_help;@;@+gubed@/
get_next←c;
end;

@ Note that the following code substitutes \.{@@\{} and \.{@@\}} for the
respective combinations `\.{(*}' and `\.{*)}'. Explicit braces should be used
for \TEX\ comments in \PASCAL\ text.

@d compress(#)==begin c←#; incr(loc); end 
@<Compress two-symbol...@>=
".": if buffer[loc]="." then compress(double_dot);
":": if buffer[loc]="=" then compress(left_arrow);
"=": if buffer[loc]="=" then compress(equivalence_sign);
">": if buffer[loc]="=" then compress(greater_or_equal);
"<": if buffer[loc]="=" then compress(less_or_equal)
	else if buffer[loc]=">" then compress(not_equal);
"(": if buffer[loc]="*" then compress(begin_comment);
"*": if buffer[loc]=")" then compress(end_comment);

@ @<Get an identifier@>=
begin if ((c="E")∨(c="e"))∧(loc>0) then
	if (buffer[loc-1]≤"9")∧(buffer[loc-1]≥"0") then c←exponent;
if c≠exponent then
	begin decr(loc); id_first←loc;
	repeat incr(loc); d←buffer[loc];
	until ((d<"0")∨((d>"9")∧(d<"A"))∨((d>"Z")∧(d<"a"))∨(d>"z")) ∧ (d≠"_");
	c←identifier; id_loc←loc;
	end;
end

@ A string that starts and ends with single or double quote marks is
scanned by the following piece of the program.

@<Get a string@>=
begin id_first←loc-1;
repeat d←buffer[loc]; incr(loc);
if loc>limit then
	begin ex_err_print('! String constant didn''t end'); 
	loc←limit; d←c;
	end;
until d=c;
id_loc←loc; c←string;
end

@ After an \.{@@} sign has been scanned, the next character tells us
whether there is more work to do.

@<Get control code and possible module name@>=
begin c←control_code(buffer[loc]); incr(loc);
if c=underline then
	begin xref_switch←def_flag; goto restart;
	end
else if c=no_underline then
	begin xref_switch←0; goto restart;
	end
else if (c≤TEX_string)∧(c≥xref_roman) then
	@<Scan to the next \.{@@>}@>
else if c=module_name then
	@<Scan the module name and make |cur_module| point to it@>;
end

@ @<Scan the module name...@>=
begin @<Put module name into |module[1..k]|@>;
if k>3 then
	begin if (module[k]=".")∧(module[k-1]=".")∧(module[k-2]=".") then
		cur_module←prefix_lookup(k-3)
	else cur_module←mod_lookup(k);
	end
else cur_module←mod_lookup(k);
end

@ Module names are placed into the |module| array with consecutive spaces,
tabs, and carriage-returns replaced by single spaces. There will be no
spaces at the beginning or the end. (We set |module[0]←" "| to facilitate
this, since the |mod_lookup| routine uses |module[1]| as the first
character of the name.)

@<Set init...@>=module[0]←" ";

@ @<Put module name...@>=
k←0;
loop	begin if loc>limit then
		begin get_line;
		if buffer[0]=form_feed then
			begin ex_err_print('! Page ended in module name');
			loc←1; goto done;
			end;
		end;
	d←buffer[loc];
	@<if end of name, |goto done|@>;
	incr(loc); if k<longest_name-1 then incr(k);
	if (d=" ")∨(d=tab_mark) then
		begin d←" "; if module[k-1]=" " then decr(k);
		end;
	module[k]←d;
	end;
done: @<Check for overlong name@>;
if (module[k]=" ")∧(k>0) then decr(k);

@ @<if end of name,...@>=
if d="@@" then
	begin d←buffer[loc+1];
	if d=">" then
		begin loc←loc+2; goto done;
		end;
	if (d=" ")∨(d=tab_mark)∨(d="*") then
		begin ex_err_print('! Module name didn''t end'); goto done;
		end;
	incr(k); module[k]←"@@"; incr(loc); {now |d=buffer[loc]| again}
	end

@ @<Check for overlong name@>=
if k≥longest_name-2 then
	begin ex_print_nl('! Module name too long: ');
	for j←1 to 25 do print(chr(module[j]));
	print('...');
	end

@ @<Scan to the next...@>=
begin id_first←loc; buffer[limit+1]←"@@";
while buffer[loc]≠"@@" do incr(loc);
id_loc←loc;
if loc>limit then 
	begin ex_err_print('! Control text didn''t end'); loc←limit;
	end
else	begin loc←loc+2;
	if buffer[loc-1]≠">" then
		err_print('! Control codes are forbidden in control text');
	end;
end
@* Phase one processing.
We now have accumulated enough subroutines to make it possible to carry out
\.{WEAVE}'s first pass over the source file. If everything works right,
both phase one and phase two of \.{WEAVE} will assign the same numbers to
modules, and these numbers will agree with what \.{TANGLE} does.

The global variable |next_control| often contains the most recent output of
|get_next|; in interesting cases, this will be the control code that
ended a module or part of a module.

@<Glob...@>=@!next_control:eight_bits; {control code waiting to be acting upon}

@ The overall processing strategy in phase one has the following straightforward
outline.

@<Phase I: Read all the user's text and store the cross references@>=
phase_one←true;
reset_input;
module_count←0;
repeat skip_limbo;
	if ¬input_has_ended then
		repeat @<Store cross reference data for the current module@>
		until next_control=page_end;
until input_has_ended;
phase_one←false;
@<Print error messages about unused or undefined module names@>;

@ @<Store cross reference data...@>=
if module_count<def_flag-1 then incr(module_count)
else overflow('module number');
@<Store cross references in the \TEX\ part of a module@>;
@<Store cross references in the definition part of a module@>;
@<Store cross references in the \PASCAL\ part of a module@>;

@ The |PASCAL_xref| subroutine stores references to identifiers in \PASCAL\
text material beginning with the current value of |next_control| and continuing
until |next_control| is `\.\{' or `\v', or until the next
``milestone'' is passed (i.e., |next_control≥format|). If |next_control≥format|
when |PASCAL_xref| is called, nothing will happen; but if |next_control="|"|
upon entry, the procedure assumes that this is the `\v' preceding
\PASCAL\ text that is to be processed.

The program uses the fact that our internal code numbers satisfy
the relations |xref_roman=identifier+roman| and |xref_typewriter=identifier+
typewriter| and |normal=0|. An implied `\.{@@!}' is inserted after
\&{function}, \&{procedure}, \&{program}, and \&{var}.

@p procedure PASCAL_xref; {makes cross references for \PASCAL\ identifiers}
label exit;
var p:name_pointer; {a referenced name}
begin while next_control<format do
	begin if (next_control≥identifier)∧(next_control≤xref_typewriter) then
		begin p←id_lookup(next_control-identifier); new_xref(p);
		if (ilk[p]=proc_like)∨(ilk[p]=var_like) then
			xref_switch←def_flag; {implied `\.{@@!}'}
		end;
	next_control←get_next;
	if (next_control="|")∨(next_control="{") then return;
	end;
exit:end;

@ The |outer_xref| subroutine is like |PASCAL_xref| but it begins
with |next_control≠"|"| and ends with |next_control≥format|. Thus, it
handles \PASCAL\ text with embedded comments.

@p procedure outer_xref; {extension of |PASCAL_xref|}
var bal:eight_bits; {brace level in comment}
begin while next_control<format do
	if next_control≠"{" then PASCAL_xref
	else	begin bal←skip_comment(1); next_control←"|";
		while bal>0 do
			begin PASCAL_xref;
			if next_control="|" then bal←skip_comment(bal)
			else bal←0; {an error will be reported in phase two}
			end;
		end;
end;

@ In the \TEX\ part of a module, cross reference entries are made only for the
identifiers in \PASCAL\ texts enclosed in \pb, or for control texts enclosed
in \.{@@\↑$\ldotsm$@@>} or \.{@@.$\ldotsm$@@>}.

@<Store cross references in the \T...@>=
repeat next_control←skip_TEX;
case next_control of
underline: xref_switch←def_flag;
no_underline: xref_switch←0;
"|": PASCAL_xref;
xref_roman, xref_typewriter, module_name:
	begin loc←loc-2; next_control←get_next; {scan to \.{@@>}}
	if next_control≠module_name then
		new_xref(id_lookup(next_control-identifier));
	end;
othercases do_nothing
endcases;
until next_control≥format

@ During the definition and \PASCAL\ parts of a module, cross references are
made for all identifiers except reserved words; however, the identifiers
in a format definition are referenced even if they are reserved. The \TEX\ code
in comments is, of course, ignored, except for \PASCAL\ portions enclosed in
\pb; the text of a module name is skipped entirely, even if it contains
\pb\ constructions.

The variables |lhs| and |rhs| point to the respective identifiers involved
in a format definition.

@<Global...@>=
@!lhs,@!rhs:name_pointer; {indices into |byte_start| for format identifiers}

@ When we get to the following code we have |next_control≥format|.

@<Store cross references in the d...@>=
while next_control≤definition do {|format| or |definition|}
	begin xref_switch←def_flag; {implied \.{@@!}}
	if next_control=definition then next_control←get_next
	else @<Process a format definition@>;
	outer_xref;
	end

@ Error messages for improper format definitions will be issued in phase
two. Our job in phase one is to define the |ilk| of a properly formatted
identifier, and to fool the |new_xref| routine into thinking that the
identifier on the right-hand side of the format definition is not a
reserved word.

@<Process a form...@>=
begin next_control←get_next;
if next_control=identifier then
	begin lhs←id_lookup(normal); ilk[lhs]←normal; new_xref(lhs);
	next_control←get_next;
	if next_control=equivalence_sign then
		begin next_control←get_next;
		if next_control=identifier then
			begin rhs←id_lookup(normal);
			ilk[lhs]←ilk[rhs]; ilk[rhs]←normal; new_xref(rhs);
			ilk[rhs]←ilk[lhs]; next_control←get_next;
			end;
		end;
	end;
end

@ Finally, when the \TEX\ and definition parts have been treated, we have
|next_control≥begin_pascal|.

@<Store cross references in the \P...@>=
if next_control≤module_name then {|begin_pascal| or |module_name|}
	begin if next_control=begin_pascal then mod_xref_switch←0
	else mod_xref_switch←def_flag;
	repeat if next_control=module_name then new_mod_xref(cur_module);
		next_control←get_next; outer_xref;
	until next_control>module_name;
	end

@ After phase one has looked at everything, we want to check that each
module name was both defined and used.
The variable |cur_xref| will point to cross references for the
current module name of interest.

@<Glob...@>=@!cur_xref:0..max_refs; {temporary cross reference pointer}

@ The following recursive procedure
walks through the tree of module names and prints out anomalies.
@↑recursion@>

@p procedure mod_check(p:name_pointer); {print anomalies in subtree $p$}
begin if p>0 then
	begin mod_check(llink[p]);@/
	cur_xref←xref[p];
	if num(cur_xref)<def_flag then
		begin ex_print_nl('! Never defined: <'); print_id(p); print('>');
		end;
	while num(cur_xref)≥def_flag do cur_xref←xlink(cur_xref);
	if cur_xref=0 then
		begin ex_print_nl('! Never used: <'); print_id(p); print('>');
		end;
	mod_check(rlink[p]);
	end;
end;

@ @<Print error messages about un...@>=@+mod_check(rlink[0])
@* Low-level output routines.
The \TEX\ output is supposed to appear in lines at most |line_length| characters
long, so we place it into an output buffer. During the output process,
|out_page| and |out_line| will hold the current page and line number of the line
about to be output.

@<Glo...@>=
@!out_buf:array[0..line_length] of ascii_code; {assembled characters}
@!out_ptr:0..line_length; {number of characters in |out_buf|}
@!out_page,@!out_line: sixteen_bits; {coordinates of next line to be output}

@ The |flush_buffer| routine empties the buffer up to a given breakpoint,
and moves any remaining characters to the beginning of the next line,
deleting a blank if it appears at the break position.
The characters emptied from the buffer form a new line of output,
except that a blank line is not written at the top of a page.

@p procedure flush_buffer(b:eight_bits); {outputs |out_buf[1..b]|,
	where |b≤out_ptr|}
var k:0..line_length;
begin if out_buf[b]=" " then decr(b);
if (b>0)∨(out_line>1) then
	begin for k←1 to b do write(chr(out_buf[k]));
	write_ln(''); incr(out_line);
	end;
if b<out_ptr then if out_buf[b+1]=" " then incr(b);
if b<out_ptr then for k←b+1 to out_ptr do out_buf[k-b]←out_buf[k];
out_ptr←out_ptr-b;
end;

@ When we are copying \TEX\ source material, we retain line breaks
that occur in the input, except that an empty line is not
output when the \TEX\ source line was nonempty. For example, a line
of the \TEX\ file that contains only an index cross-reference entry
will not be copied. The |finish_line| routine is called just before
|get_line| inputs a new line, and just after a line break token has
been emitted during the output of translated \PASCAL\ text.

@d finish_line==
	begin if (out_ptr>0)∨(limit=0) then flush_buffer(out_ptr);
	end

@d ex_finish_line==if (out_ptr>0)∨(limit=0) then flush_buffer(out_ptr);

@ In particular, the |finish_line| procedure is called near the very
beginning of phase two. We initialize the output variables in a slightly
tricky way so that the first line of the output file will be
`\.{\\input webhdr}'.

@<Set init...@>=
out_ptr←1; out_page←1; out_line←1; out_buf[1]←"r"; write('\input webhd');

@ The |write_end_of_page| procedure is called when a page mark goes into the
output. \.{WEAVE} tries to preserve the page structure of the \.{WEB}
file in the \.{TEX} file by calling this routine at appropriate times.

@p procedure write_end_of_page;
begin if out_ptr>0 then flush_buffer(out_ptr);
stanford if omit_page then omit_page←false@+else@+drofnats@;
	begin write(chr(form_feed)); {write a page mark}
	incr(out_page); out_line←1;
	end;
end;

@ When we wish to append the character $c$ to the output buffer, we write
`$|out|(c)$'; this will cause the buffer to be emptied if it was already
full. Similarly, `$|out2|(c↓1)(c↓2)$' appends a pair of characters.
A line break will occur at a space or after a single-nonletter
\TEX\ control sequence.

@d oot(#)==if out_ptr=line_length then break_out;
	incr(out_ptr); out_buf[out_ptr]←#;
@d oot1(#)==oot(#)@+end
@d oot2(#)==oot(#)@,oot1
@d oot3(#)==oot(#)@,oot2
@d oot4(#)==oot(#)@,oot3
@d oot5(#)==oot(#)@,oot4
@d out==@+begin oot1
@d out2==@+begin oot2
@d out3==@+begin oot3
@d out4==@+begin oot4
@d out5==@+begin oot5

@ The |break_out| routine is called just before the output buffer is about
to overflow. To make this routine a little faster, we initialize position
0 of the output buffer to `\.\\'; this character isn't really output.

@<Set init...@>=
out_buf[0]←"\";

@ Note that the \TEX\ construction `\.{\\\\\{}' does not necessarily involve
the control sequence `\.{\\\{}', so |break_out| needs to check to see
whether or not `\.{\\}' is preceded by another `\.{\\}'.

@p procedure break_out; {finds a way to break the output line}
label found;
var k:0..line_length; {index into |out_buf|}
@!c,@!d:ascii_code; {characters from the buffer}
begin k←out_ptr; d←out_buf[k];
while d≠" " do
	begin decr(k); c←out_buf[k];
	if c="\" then
		if k=0 then @<Print error message and prepare to
				write the entire unbroken line@>
		else if (((d<"A")∨((d>"Z")∧(d<"a"))∨(d>"z"))∧
				(out_buf[k-1]≠"\")) then
			begin incr(k); c←" "; {OK to break at $k$}
			end;
	d←c;
	end;
flush_buffer(k); {since |k>0|, this leaves a non-full buffer}
end;

@ We can cause the |break_out| algorithm to write out the whole line by
setting |k←out_ptr| and |c←" "|.

@<Print error message and prepare to write...@>=
begin ex_print_nl('! Line had to be broken (output p.',out_page:0,
	',l.',out_line:0); print_ln('):');
for k←1 to out_ptr do print(chr(out_buf[k]));
print_ln(''); k←out_ptr; c←" ";
end

@ Here is a procedure that outputs a decimal number. It is used to
generate module numbers in cross references.

@<Glob...@>=@!dig:array[0..4] of 0..9; {digits to output}

@ The number to be converted by |out_val| is known to be less than |def_flag|,
so it cannot have more than five decimal digits.

@p procedure out_val(v:sixteen_bits); {output a nonnegative integer}
var k:0..5; {index into |dig|}
begin k←0;
repeat dig[k]←v mod 10; v←v div 10; incr(k);
until v=0;
repeat decr(k); out(dig[k]+"0");
until k=0;
end;

@ The |out_name| subroutine is used to output an identifier or index entry,
enclosing it in braces.

@p procedure out_name(p:name_pointer); {outputs a name}
var k:0..max_bytes; {index into |byte_mem|}
begin out("{");
for k←byte_start[cur_name] to byte_start[cur_name+1]-1 do out(byte_mem[k]);
out("}");
end;
@* Routines that copy \TEX\ material.
During phase two, we use the subroutines |copy_limbo|, |copy_TEX|, and
|copy_comment| in place of the analogous procedures called
|skip_limbo|, |skip_TEX|, and |skip_comment| that were used in phase one.

The |copy_limbo| routine, for example, takes \TEX\ material that is not part
of any module and moves it from the |input| file to the |output| file.
No `\.{@@}' signs should occur in such material except in `\.{@@@@}' pairs;
such pairs are replaced by singletons. 

@p procedure copy_limbo; {copy \TEX\ code until the next module begins}
label exit;
var c:ascii_code; {character following \.{@@} sign}
begin loop if loc>limit then
		begin ex_finish_line; get_line;
		if buffer[0]=form_feed then
			begin if input_has_ended then return;
			write_end_of_page; loc←1;
			end;
		end
	else	begin buffer[limit+1]←"@@";
		@<Copy up to control code, |return| if finished@>;
		end;
exit:end;

@ @<Copy up to control...@>=
while buffer[loc]≠"@@" do
	begin out(buffer[loc]); incr(loc);
	end;
if loc≤limit then
	begin loc←loc+2; c←buffer[loc-1];
	if (c=" ")∨(c=tab_mark)∨(c="*") then return;
	out("@@");
	if c≠"@@" then err_print('! Double @@ required outside of modules');
	end

@ The |copy_TEX| routine processes the \TEX\ code at the beginning of a module;
for example, the words you are now reading were copied in this way. It returns
the next control code or `\v' or end-of-page found in the input.

@p function copy_TEX:eight_bits; {copy pure \TEX\ material}
label done;
var c:eight_bits; {control code found}
begin loop begin if loc>limit then
		begin ex_finish_line; get_line;
		if buffer[0]=form_feed then
			begin loc←1; c←page_end; goto done;
			end;
		end;
	buffer[limit+1]←"@@";
	@<Copy up to `\v' or control code, |goto done| if finished@>;
	end;
done:copy_TEX←c;
end;

@ We don't copy spaces or tab marks into the beginning of a line. This makes the
test for empty lines in |finish_line| work.

@<Copy up to `\v'...@>=
repeat c←buffer[loc]; incr(loc);
if c="|" then goto done;
if c≠"@@" then
	begin out(c);
	if (out_ptr=1)∧((c=" ")∨(c=tab_mark)) then decr(out_ptr);
	end;
until c="@@";
if loc≤limit then
	begin c←control_code(buffer[loc]); incr(loc);
	if c="@@" then out("@@");
	goto done;
	end

@ The |copy_comment| uses and returns a brace-balance value, following the
conventions of |skip_comment| above. Instead of copying the \TEX\ material
into the output buffer, this procedure copies it into the token memory.
The abbreviation |app_tok(t)| is used to append token $t$ to the current
token list, and it also makes sure that it is possible to append at least
one further token without overflow.

@d app_tok(#)==begin if tok_ptr+2>max_toks then overflow('token');
	tok_mem[tok_ptr]←#; incr(tok_ptr);
	end

@d ex_app_tok(#)==if tok_ptr+2>max_toks then overflow('token');
	tok_mem[tok_ptr]←#; incr(tok_ptr)

@p function copy_comment(bal:eight_bits):eight_bits; {copies \TEX\ code in
	comments}
label done;
var c:ascii_code; {current character being copied}
begin loop begin if loc>limit then
		begin get_line;
		if buffer[0]=form_feed then
			begin ex_err_print('! Page ended in mid_comment'); loc←1;
			@<Clear |bal| and |goto done|@>;
			end;
		end;
	c←buffer[loc]; incr(loc);
	if c="|" then goto done;
	ex_app_tok(c);
	@<Copy special things when |c="@@", "\", "{", "}"|;
		|goto done| at end@>;
	end;
done: copy_comment←bal;
end;

@ @<Copy special things when |c="@@"...@>=
if c="@@" then
	begin incr(loc);
	if buffer[loc-1]≠"@@" then
		begin ex_err_print('! Illegal use of @@ in comment');
		loc←loc-2; decr(tok_ptr); @<Clear |bal|...@>;
		end;
	end
else if (c="\")∧(buffer[loc]≠"@@") then
	begin ex_app_tok(buffer[loc]); incr(loc);
	end
else if c="{" then incr(bal)
else if c="}" then
	begin decr(bal);
	if bal=0 then goto done;
	end

@ When the comment has terminated abruptly due to an error, we output
enough right braces to keep \TEX\ happy.

@<Clear |bal|...@>=
ex_app_tok(" "); {this is done in case the previous character was `\.\\'}
repeat ex_app_tok("}"); decr(bal);
until bal=0;
goto done;
@* Parsing.
The most intricate part of \.{WEAVE} is its mechanism for converting
\PASCAL-like code into \TEX\ code, and we might as well plunge into this
aspect of the program now. A ``bottom up'' approach is used to parse the
\PASCAL-like material, since \.{WEAVE} must deal with fragmentary
constructions whose overall ``part of speech'' is not known.

At the lowest level, the input is represented as a sequence of entities that
we shall call {\it scraps}, where each scrap of information consists of
two parts, its {\it category} and its {\it translation}. The category is
essentially a syntactic class, and the translation is a token list that
represents \TEX\ code. Rules of syntax and semantics tell us how to combine
adjacent scraps into larger ones, and if we are lucky an entire \PASCAL\ text
that starts out as hundreds of small scraps will join together into one
gigantic scrap whose translation is the desired \TEX\ code. If we are
unlucky, we will be left with several scraps that don't combine; their
translations will simply be output, one by one.

The combination rules are given as context-sensitive productions that are
applied from left to right. Suppose that we are currently working on the
sequence of scraps $s↓1\,s↓2\ldotsm s↓n$. We try first to find the longest
production that applies to an initial substring $s↓1\,s↓2\ldotsm$; but if no
such productions exist, we find to find the longest production applicable to
the next substring $s↓2\,s↓3\ldotsm$; and if that fails, we try to match
$s↓3\,s↓4\ldotsm$, etc.

A production applies if the category codes have a given pattern. For example,
one of the productions is
$$|open|\;|math|\;|semi|\;→\;|open|\;|math|$$
and it means that three consecutive scraps whose respective categories are
|open|, |math|, and |semi| are converted to two scraps whose categories
are |open| and |math|. This production also has an associated rule that
tells how to combine the translation parts:
$$\eqalign{O↓2⊗=O↓1\cr
M↓2⊗=M↓1\,S\,\.{\\,}\,\hbox{|opt|}\,5\cr}$$
This means that the |open| scrap has not changed, while the new |math| scrap
has a translation $M↓2$ composed of the translation $M↓1$ of the original
|math| scrap followed by the translation $S$
of the |semi| scrap followed by `\.{\\,}' followed
by `|opt|' followed by `\.5'. (In the \TEX\ file, this will specify an additional
thin space after the semicolon, followed by an optional line break with
penalty 50.) Translation rules use subscripts to distinguish between
translations of scraps whose categories have the same initial letter;
these subscripts are assigned from left to right.

$\.{WEAVE}$ also has the production rule
$$|semi|\;→\;|terminator|$$
(meaning that a semicolon can terminate a \PASCAL\ statement). Since productions
are applied from left to right, this rule will be activated only if the |semi|
is not preceded by scraps that match other productions; in particular, a |semi|
that is preceded by `|open| |math|' will have disappeared because of the
production above, and such semicolons do not act as statement terminators.
This incidentally is how \.{WEAVE} is able to treat semicolons in two
distinctly different ways, the first of which is intended for semicolons in
the parameter list of a procedure declaration.

The translation rule corresponding to $|semi|\;→\;|terminator|$ is
$$T=S$$
but we shall not mention translation rules in the common case that the
translation of the new scrap on the right-hand side is simply the
concatenation of the disappearing scraps on the left-hand side.

@ Here is a list ∂f the category codes that scraps can have.

@d simp=1 {the translation can be used both in horizontal mode
	and in math mode of \TEX}
@d math=2 {the translation should be used only in \TEX\ math mode}
@d intro=3 {a statement is expected to follow this, after a space and
	an optional break}
@d open=4 {denotes an incomplete parenthesized quantity to be used in
	math mode}
@d beginning=5 {denotes an incomplete compound statement to be used in
	horizontal mode}
@d close=6 {ends a parenthesis or compound statement}
@d alpha=7 {denotes the beginning of a clause}
@d omega=8 {denotes the ending of a clause and possible comment following}
@d semi=9 {denotes a semicolon and possible comment following it}
@d terminator=10 {something that ends a statement or declaration}
@d stmt=11 {denotes a statement or declaration including its terminator}
@d cond=12 {precedes an \&{if} clause that might have a matching \&{else}}
@d clause=13 {precedes a statement after which indentation ends}
@d colon=14 {denotes a colon}
@d exp=15 {stands for the E in a floating point constant}
@d proc=16 {denotes a procedure or program or function heading}
@d case_head=17 {denotes a case statement or record heading}
@d record_head=18 {denotes a record heading without indentation}
@d var_head=19 {denotes a variable declaration heading}
@d elsie=20 {\&{else}}
@d casey=21 {\&{case}}
@d mod_scrap=22 {denotes a module name}

@p debug procedure print_cat(c:eight_bits); {symbolic printout of a category}
begin case c of
simp: print('simp');
math: print('math');
intro: print('intro');
open: print('open');
beginning: print('beginning');
close: print('close');
alpha: print('alpha');
omega: print('omega');
semi: print('semi');
terminator: print('terminator');
stmt: print('stmt');
cond: print('cond');
clause: print('clause');
colon: print('colon');
exp: print('exp');
proc: print('proc');
case_head: print('casehead');
record_head: print('recordhead');
var_head: print('varhead');
elsie: print('elsie');
casey: print('casey');
mod_scrap: print('module');
othercases print('UNKNOWN')
endcases;
end;
gubed

@ The token lists for translated \TEX\ output contain some special control
symbols as well as ordinary characters. These control symbols are interpreted
by \.{WEAVE} before they are written to the output file.

\yskip\hang |break| denotes an optional line break or an en space;

\yskip\hang |force| denotes a line break;

\yskip\hang |big_force| denotes a line break with additional vertical space;

\yskip\hang |opt| denotes an optional line break (with the continuation line
	indented two ems with respect to the normal starting position)---this
	code is followed by an integer $n$, and the break will occur with
	penalty $10n$;

\yskip\hang |backup| denotes a backspace of one em;

\yskip\hang |cancel| obliterates any |break| or |force| or |big_force|
tokens that immediately precede or follow it and also cancels any
|backup| tokens that follow it;

\yskip\hang |indent| causes future lines to be indented one more em;

\yskip\hang |outdent| causes future lines to be indented one less em.

\yskip\noindent All of these tokens are removed from the \TEX\ output that
comes from \PASCAL\ text between \pb\ signs; |break| and |force| and |line_break|
become single spaces in this mode. The translation of other \PASCAL\ texts
results in \TEX\ control sequences \.{\\1}, \.{\\2}, \.{\\3}, \.{\\4}, \.{\\5},
\.{\\6}, \.{\\7} corresponding respectively to |indent|, |outdent|, |opt|,
|backup|, |break|, |force|, and |big_force|. However, a sequence of consecutive
|break|, |force|, and/or |big_force| tokens is first replaced by a single
token (the maximum of the given ones).

The tokens |math_rel|, |math_bin|, |math_op| will be translated into
\.{\\mathrel\{}, \.{\\mathbin\{}, and \.{\\mathop\{}, respectively.
Other control sequences in the \TEX\ output will be `\.{\\\\\{}$\ldotsm$\.\}'
surrounding identifiers, `\.{\\&\{}$\ldotsm$\.\}' surrounding reserved words,
`\.{\\.\{}$\ldotsm$\.\}' surrounding strings, `\.{\\C\{}$\ldotsm$\.\}$\,$|force|'
surrounding comments, and `\.{\\X$n$:}$\ldotsm$\.{\\X}' surrounding module names,
where $n$ is the module number.

@d math_bin=@'203
@d math_rel=@'204
@d math_op=@'205
@d big_cancel=@'206 {like |cancel|, also overrides spaces}
@d cancel=@'207 {overrides |backup|, |break|, |force|, |big_force|}
@d indent=cancel+1 {one more tab (\.{\\1})}
@d outdent=cancel+2 {one less tab (\.{\\2})}
@d opt=cancel+3 {optional break in mid-statement (\.{\\3})}
@d backup=cancel+4 {stick out one unit to the left (\.{\\4})}
@d break=cancel+5 {optional break between statements (\.{\\5})}
@d force=cancel+6 {forced break between statements (\.{\\6})}
@d big_force=cancel+7 {forced break with additional space (\.{\\7})}
@d end_translation=big_force+1 {special sentinel token at end of list}

@ The raw input is converted into scraps according to the following table,
which gives category codes followed by the translations. Sometimes a single
item of input produces more than one scrap.
\def\*{\.{**}} (The symbol `\*' stands for `\.{\\&\{{\rm identifier}\}}', i.e.,
the identifier itself treated as a reserved word. In a few cases the category
is given as `|comment|'; this is not an actual category code, it means that
the translation will be treated as a comment, as explained below.)

\yskip\halign{\quad#\hfil⊗\quad\!#\hfil\cr
$ε$⊗|math:|\.{\\in}\cr
\.{<>}⊗|math:|\.\≠\cr
\.{<=}⊗|math:|\.\≤\cr
\.{>=}⊗|math:|\.\≥\cr
\.{:=}⊗|math:|\.\←\cr
\.{==}⊗|math: ==|\cr
\.{(*}⊗|math:|\.{\\B}\cr
\.{*)}⊗|math:|\.{\\T}\cr
\."$\,$string$\,$\."⊗|simp:|\.{\\.\{"{\rm$\,$modified string$\,$}"\}}\cr
\.\'$\,$string$\,$\.\'⊗|simp:|\.{\\.\{\\\'{\rm$\,$modified
	string$\,$}\\\'\}}\cr
\#⊗|math:|\.{\\\#}\cr
\.\$⊗|math:|\.{\\\$}\cr
\.\%⊗|math:|\.{\\\%}\cr
\.\↑⊗|math:|\.{\\\↑}\cr
\.(⊗|open:|\.(\cr
\.)⊗|close:|\.)\cr
\.[⊗|open:|\.[\cr
\.]⊗|close:|\.]\cr
\.*⊗|math:|\.{\\ast}\cr
\.,⊗|math:|\.,|@,opt@,|\.9\cr
\.{..}⊗|math:|\.{\\to}\cr
\..⊗|simp:|\..\cr
\.:⊗|colon:|\.:\cr
\.;⊗|semi:|\.;\cr
identifier⊗|simp:|\.{\\\\\{{\rm$\,$identifier$\,$}\}}\cr
\.E in constant⊗|exp:|\.{\\E\{}\cr
digit $d$⊗|simp:|$d$\cr
other character $c$⊗|math:|$c$\cr
\.{and}⊗|math:∧|\cr
\.{array}⊗|alpha:|\*\cr
\.{begin}⊗|beginning:|$|force|\,\*\,|cancel|$\qquad|intro:|\cr
\.{case}⊗|casey:|\qquad|alpha:|$|force|\,\*$\cr
\.{const}⊗|intro:|$|force|\,|backup|\,\*$\cr
\.{div}⊗|math:|$|math_bin|\,\*\,\.\}$\cr
\.{do}⊗|omega:|\*\cr
\.{downto}⊗|math:|$|math_rel|\,\*\,\.\}$\cr
\.{else}⊗|terminator:|\qquad|elsie:|$|force|\,|backup|\,\*$\cr
\.{end}⊗|terminator:|\qquad|close:|$|force|\,\*$\cr
\.{file}⊗|alpha:|\*\cr
\.{for}⊗|alpha:|$|force|\,\*$\cr
\.{function}⊗|proc:|$|force|\,|backup|\,\*\,|cancel|$\qquad
	|intro:|$|indent|\,\.{\\\ }$\cr
\.{goto}⊗|intro:|\*\cr
\.{if}⊗|cond:|\qquad|alpha:|$|force|\,\*$\cr
\.{in}⊗|math:|\.{\*in}\cr
\.{label}⊗|intro:|$|force|\,|backup|\,\*$\cr
\.{mod}⊗|math:|$|math_bin|\,\*\,\.\}$\cr
\.{nil}⊗|simp:|\*\cr
\.{not}⊗|math:|$¬$\cr
\.{of}⊗|omega:|\*\cr
\.{or}⊗|math:|$∨$\cr
\.{packed}⊗|intro:|\*\cr
\.{procedure}⊗|proc:|$|force|\,|backup|\,\*\,|cancel|$\qquad
	|intro:|$|indent|\,\.{\\\ }$\cr
\.{program}⊗|proc:|$|force|\,|backup|\,\*\,|cancel|$\qquad
	|intro:|$|indent|\,\.{\\\ }$\cr
\.{record}⊗|record_head:|\*\qquad|intro:|\cr
\.{repeat}⊗|beginning:|$|force|\,|indent|\,\*\,|cancel|$\qquad|intro:|\cr
\.{set}⊗|alpha:|\*\cr
\.{then}⊗|omega:|\*\cr
\.{to}⊗|math:|$|math_rel|\,\*\,\.\}$\cr
\.{type}⊗|intro:|$|force|\,|backup|\,\*$\cr
\.{until}⊗|terminator:|\qquad|close:|$|force|\,|backup|\,\*$\qquad|clause:|\cr
\.{var}⊗|var_head:|$|force|\,|backup|\,\*\,|cancel|$\qquad|intro:|\cr
\.{while}⊗|alpha:|$|force|\,\*$\cr
\.{with}⊗|alpha:|$|force|\,\*$\cr
\.{xclause}⊗|clause:|$|force|\,|indent|\,\*$\cr
\.{@@\'}⊗|simp:|\.{\\O}\cr
\.{@@,}⊗|math:|\.{\\,}\cr
\.{@@t}$\,$stuff$\,$\.{@@>}⊗|simp:|\.{\\hbox\{{\rm$\,$stuff$\,$}\}}\cr
\.{@@<}$\,$module$\,$\.{@@>}⊗|mod_scrap:|\.{\\X$n$:{\rm$\,$module$\,$}\\X}\cr
\.{@@\#}⊗|comment:||big_force|\cr
\.{@@/}⊗|comment:||force|\cr
\.{@@+}⊗|comment:|$|big_cancel|\,\.{\\\ }\,|big_cancel|$\cr
\.{@@;}⊗|semi:|\cr
\.{@@&}⊗|math:|\.{\\J}\cr
\.{@@\{}⊗|math:|\.{\\B}\cr
\.{@@\}}⊗|math:|\.{\\T}\cr}
\yskip\noindent When a string is output, certain characters are preceded by
`\.\\' signs so that they will print properly.

A comment in the input will be combined with the preceding
|omega| or |semi| scrap, or with the following |terminator| scrap, if
possible; otherwise it will be inserted as a separate |terminator| scrap.
An additional ``comment'' is effectively appended at the end of the
\PASCAL\ text, just before translation begins; this consists of a |cancel|
token in the case of \PASCAL\ text in \pb, otherwise it consists of a
|force| token.

From this table it is evident that \.{WEAVE} will parse a lot of non-\PASCAL\
programs. For example, the reserved words `\.{for}' and `\.{array}' are
treated in an identical way by \.{WEAVE} from a syntactic standpoint,
and semantically they are equivalent except that a forced line break occurs
just before `\&{for}'; \PASCAL\ programmers may well be surprised at this
similarity. The idea is to keep \.{WEAVE}'s rules as simple as possible,
consistent with doing a reasonable job on syntactically correct \PASCAL\
programs. The production rules below have been formulated in the same
spirit of ``almost anything goes.''

@ Here is a table of all the productions. The reader can best get a feel for
how they work by trying them out by hand on small examples; no amount of
explanation will be as effective as watching the rules in action.

\def\[#1]{\quad$\dleft#1\dright$}
\def\sp{\.{\ }}
\yskip\halign to size{\hfil\it# ⊗#\hfil\hskip-200pt\tabskip 0pt plus 100pt
	⊗\!#\hfil\tabskip0pt\cr
⊗Production categories\[\hbox{translations}]⊗Remarks\cr
\noalign{\yskip}
1⊗|alpha@,math@,colon| $→$ |alpha@,math|⊗e.g., |case v:boolean of|\cr
2⊗|alpha@,math@,omega| $→$ |clause|\[C=A\,\sp\,\.\$\,M\,\.\$\,\sp\,|indent|\,
O]⊗e.g., |while x>0 do|\cr
3⊗|alpha@,omega| $→$ |clause|\[C=A\,\sp\,|indent|\,O]⊗e.g., |file of|\cr
4⊗|alpha@,simp| $→$ |alpha@,math|⊗convert to math mode\cr
5⊗|beginning@,close@,(terminator@t or @>stmt)| $→$ |stmt|⊗compound statement
ends\cr
6⊗|beginning@,stmt| $→$ |beginning|\[B↓2=B↓1\,|break|\,S]⊗compound statement
grows\cr
7⊗|case_head@,casey@,clause| $→$ |case_head|\[C↓4=C↓1\,|outdent|\,C↓2\,C↓3]⊗\!
variant records\cr
8⊗|case_head@,close@,terminator| $→$ |stmt|\[S=C↓1\,|cancel|\,|outdent|\,
C↓2\,T]⊗end of case statement\cr
9⊗|case_head@,stmt| $→$ |case_head|\[C↓2=C↓1\,|force|\,S]⊗case statement grows\cr
10⊗|casey@,clause| $→$ |case_head|⊗beginning of case statement\cr
11⊗|clause@,stmt| $→$ |stmt|\[S↓2=C\,|break|\,S↓1\,|cancel|\,|outdent|\,
|force|]⊗end of controlled statement\cr
12⊗|cond@,clause@,stmt@,elsie| $→$ |clause|\[C↓3=C↓1\,C↓2\,|break|\,S\,E\,
\sp\,|cancel|]⊗complete conditional\cr
13⊗|cond@,clause@,stmt| $→$ |stmt|\[S↓2=C↓1\,C↓2\,|break|\,S↓1\,|cancel|\,
|outdent|\,|force|]⊗incomplete conditional\cr
14⊗|elsie| $→$ |intro|⊗unmatched else\cr
15⊗|exp@,math@,simp| $→$ |math|\[M↓2=E\,M↓1\,S\,\.\}]⊗signed exponent\cr
16⊗|exp@,simp| $→$ |math|\[M=E\,S\,\.\}]⊗unsigned exponent\cr
17⊗|intro@,stmt| $→$ |stmt|\[S↓2=I\,\sp\,|opt|\,\.7\,|cancel|\,S↓1]⊗labeled
statement, etc.\cr
18⊗|math@,colon| $→$ |intro|\[I=|force|\,|backup|\,\.\$\,M\,\.\$\,C]⊗compound
label\cr
19⊗|math@,math| $→$ |math|⊗simple concatenation\cr
20⊗|math@,simp| $→$ |math|⊗simple concatenation\cr
21⊗|math@,terminator| $→$ |stmt|\[S=\.\$\,M\,\.\$\,T]⊗statement involving math\cr
22⊗|mod_scrap@,(terminator@t or @>semi)| $→$ |stmt|\[S=M\,T\,|force|]⊗module
like a statement\cr
23⊗|mod_scrap| $→$ |simp|⊗module unlike a statement\cr
24⊗|open@,casey| $→$ |casey|\[C↓2=O\,|cancel|\,C↓1]⊗case in field list\cr
25⊗|open@,close| $→$ |math|\[M=O\,\.\\\,\.,\,C]⊗empty set |[]|\cr
26⊗|open@,math@,casey| $→$ |casey|⊗case in field list\cr
27⊗|open@,math@,close| $→$ |math|⊗parenthesized group\cr
28⊗|open@,math@,colon| $→$ |open@,math|⊗colon in parentheses\cr
29⊗|open@,math@,proc@,intro| $→$ |open@,math|\[M↓2=M↓1\,|math_op|\,|cancel|\,
P\,\.\}]⊗|procedure| in parentheses\cr
30⊗|open@,math@,semi| $→$ |open@,math|\[M↓2=M↓1\,S\,\.\\\,\.,\,|opt|\,
\.5]⊗semicolon in parentheses\cr
31⊗|open@,math@,var_head@,intro| $→$ |open@,math|\[M↓2=M↓1\,|math_op|\,
|cancel|\,V\,\.\}]⊗|var| in parentheses\cr
32⊗|open@,proc@,intro| $→$ |open@,math|\[M=|math_op|\,|cancel|\,
P\,\.\}]⊗|procedure| in parentheses\cr
33⊗|open@,simp| $→$ |open@,math|⊗convert to math mode\cr
34⊗|open@,var_head@,intro| $→$ |open@,math|\[M=|math_op|\,|cancel|\,V\,
\.\}]⊗|var| in parentheses\cr
35⊗|proc@,beginning@,close@,terminator| $→$ |stmt|\[S=P\,|cancel|\,
|outdent|\,B\,C\,T]⊗end of procedure declaration\cr
36⊗|proc@,stmt| $→$ |proc|\[P↓2=P↓1\,|break|\,S]⊗procedure declaration
grows\cr
37⊗|record_head@,intro@,casey| $→$ |casey|\[C↓2=R\,I\,\sp\,|cancel|\,C↓1]⊗\!
\&{record case} $\ldots$\cr
38⊗|record_head| $→$ |case_head|\[C=|indent|\,R\,|cancel|]⊗other \&{record}
structures\cr
39⊗|semi| $→$ |terminator|⊗semicolon after statement\cr
40⊗|simp@,colon| $→$ |intro|\[I=|force|\,|backup|\,S\,C]⊗simple label\cr
41⊗|simp@,math| $→$ |math|⊗simple concatenation\cr
42⊗|simp@,mod_scrap| $→$ |mod_scrap|⊗in emergencies\cr
43⊗|simp@,simp| $→$ |simp|⊗simple concatenation\cr
44⊗|simp@,terminator| $→$ |stmt|⊗simple statement\cr
45⊗|stmt@,stmt| $→$ |stmt|\[S↓3=S↓1\,|break|\,S↓2]⊗adjacent statements\cr
46⊗|terminator| $→$ |stmt|⊗empty statement\cr
47⊗|var_head@,beginning| $→$ |stmt@,beginning|⊗end of variable
declarations\cr
48⊗|var_head@,math@,colon| $→$ |var_head@,intro|\[I=\.\$\,M\,\.\$\,C]⊗\!
variable declaration\cr
49⊗|var_head@,simp@,colon| $→$ |var_head@,intro|⊗variable declaration\cr
50⊗|var_head@,stmt| $→$ |var_head|\[V↓2=V↓1\,|break|\,S]⊗variable
declarations grow\cr}
\yskip\noindent
Translations are not specified here when they are simple concatenations
of the scraps that change. For example, the full translation of
`|open@,math@,colon| $→$ |open@,math|' is $O↓2=O↓1$, $M↓2=M↓1C$.
@* Implementing the productions.
When \PASCAL\ text is to be processed with the grammar above, we put its
initial scraps $s↓1\ldotsm s↓n$ into two arrays |cat[1..n]| and |trans[1..n]|.
The value of |cat[k]| is simply a category code from the list above; the
value of |trans[k]| is a text pointer, i.e., an index into |tok_start|.
Our production rules have the nice property that the right-hand side is never
longer than the left-hand side. Therefore it is convenient to use sequential
allocation for the current sequence of scraps. Five pointers are used to
manage the parsing:

\yskip\hang |pp| (the parsing pointer) is such that we are trying to match
the category codes |cat[pp]@,cat[pp+1]|$\ldotsm$ to the left-hand sides
of productions.

\yskip\hang |scrap_base|, |lo_ptr|, |hi_ptr|, and |scrap_ptr| are such that
the current sequence of scraps appears in positions |scrap_base| through
|lo_ptr| and |hi_ptr| through |scrap_ptr|, inclusive, in the |cat| and
|trans| arrays. Scraps located between |scrap_base| and |lo_ptr| have
been examined, while those in positions |≥hi_ptr| have not yet been
looked at by the parsing process.

\yskip\noindent Initially |scrap_ptr| is set to the position of the final
scrap to be parsed, and it doesn't change its value. The parsing process
makes sure that |lo_ptr≥pp+3|, since productions have as many as four terms,
by moving scraps from |hi_ptr| to |lo_ptr|. If there are
fewer than |pp+3| scraps left, the positions up to |pp+3| are filled with
blanks that will not match in any productions. Parsing stops when
|pp=lo_ptr+1| and |hi_ptr=scrap_ptr+1|.

@<Glo...@>=
@!cat:array[0..max_scraps] of eight_bits; {category codes of scraps}
@!trans:array[0..max_scraps] of text_pointer; {translation texts of scraps}
@!pp:0..max_scraps; {current position for reducing productions}
@!scrap_base:0..max_scraps; {beginning of the current scrap sequence}
@!scrap_ptr:0..max_scraps; {ending of the current scrap sequence}
@!lo_ptr:0..max_scraps; {last scrap that has been examined}
@!hi_ptr:0..max_scraps; {first scrap that has not been examined}
stat@!max_scr_ptr:0..max_scraps; {largest value assumed by |scrap_ptr|}
tats

@ @<Set init...@>=
scrap_base←1; scrap_ptr←0;
stat max_scr_ptr←0; @+tats

@ Token lists in |@!tok_mem| are composed of the following kinds of
items for \TEX\ output.

\yskip\item{$\bullet$}ascii codes and special codes like |force| and |math_rel|
represent themselves;

\item{$\bullet$}|id_flag+p| represents \.{\\\\\{{\rm identifier $p$}\}};

\item{$\bullet$}|res_flag+p| represents \.{\\&\{{\rm identifier $p$}\}};

\item{$\bullet$}|mod_flag+p| represents module name $p$;

\item{$\bullet$}|tok_flag+p| represents token list number $p$;

\item{$\bullet$}|inner_tok_flag+p| represents token list number $p$, to be
translated without line-break controls.

@d id_flag=10240 {signifies an identifier}
@d res_flag=id_flag+id_flag {signifies a reserved word}
@d mod_flag=res_flag+id_flag {signifies a module name}
@d tok_flag==mod_flag+id_flag {signifies a token list}
@d inner_tok_flag==tok_flag+id_flag {signifies a token list in `\pb'}
@#
@d lbrace==chr("{") {this avoids possible \PASCAL\ compiler confusion}
@d rbrace==chr("}") {because these braces might occur within comments}

@p debug procedure print_text(p:text_pointer); {prints a token list}
var j:0..max_toks; {index into |tok_mem|}
@!r:0..id_flag-1; {remainder of token after the flag has been stripped off}
begin if p≥text_ptr then print('BAD')
else for j←tok_start[p] to tok_start[p+1]-1 do
	begin r←tok_mem[j] mod id_flag;
	case tok_mem[j] div id_flag of
	1: begin print('\\',lbrace); print_id(r); print(rbrace);
		end; {|id_flag|}
	2: begin print('\&',lbrace); print_id(r); print(rbrace);
		end; {|res_flag|}
	3: begin print('<'); print_id(r); print('>');
		end; {|mod_flag|}
	4: print('[[',r:0,']]'); {|tok_flag|}
	5: print('|[[',r:0,']]|'); {|inner_tok_flag|}
	othercases @<Print $r$ in symbolic form@>
	endcases;
	end;
end;
gubed

@ @<Print $r$...@>=
case r of
math_bin: print('\mathbin',lbrace);
math_rel: print('\mathrel',lbrace);
math_op: print('\mathop',lbrace);
big_cancel: print('[ccancel]');
cancel: print('[cancel]');
indent: print('[indent]');
outdent: print('[outdent]');
backup: print('[backup]');
opt: print('[opt]');
break: print('[break]');
force: print('[force]');
big_force: print('[fforce]');
end_translation: print('[quit]');
othercases print(chr(r))
endcases

@ The production rules listed above are embedded directly into the \.{WEAVE}
program, since it is easier to do this than to write an interpretive system
that would handle production systems in general. Several macros are defined
here so that the program for each production is fairly short.

All of our productions conform to the general notion that some $k$ consecutive
scraps starting at some position $j$ are to be replaced by a single scrap
of some category $c$ whose translations is composed from the translations
of the disappearing scraps. After this production has been applied, the
production pointer |pp| should change by an amount |d|. Such a production
can be represented by the quadruple $(j,k,c,d)$. For example, the production
`|simp@,math| $→$ |math|' would be represented by `$(|pp|,2,|math|,-1)$'; in
this case the pointer $pp$ should decrease by 1 after the production has
been applied, because some productions with |math| in their second positions
might now match, but no productions have |math| in the third or fourth
position of their left-hand sides. Note that the value of $d$ is determined
by the whole collection of productions, not by an individual one. Consider
the further example `|var_head@,math@,colon| $→$ |var_head@,intro|', which
is represented by `$(|pp|+1,2,|intro|,+1)$'; the $+1$ here is deduced by looking
at the grammar and seeing that no matches could possibly occur at positions
|≤pp| after this production has been applied. The determination of $d$ has
been done by hand in each case, based on the full set of productions but not
on the grammar of \PASCAL\ or on the rules for constructing the initial scraps.

We also attach a serial number of each production, so that additional
information is available when debugging. For example, the program below
contains the statement `|reduce(pp+1,2,intro,+1)(48)|' when it implements
the production just mentioned.

Before calling |reduce|, the program should have appended the tokens of the
new translation to the |tok_mem| array. We commonly want to append copies
of several existing translations, and macros are defined to simplify
these common cases. For example, |app2(pp)| will append the translations
of two consecutive scraps, |trans[pp]| and |trans[pp+1]|, to the current
token list. If the entire new translation is formed in this way,
we write `$|squash|(j,k,c,d)$' instead of `$|reduce|(j,k,c,d)$'. For example,
`|squash(pp,2,math,-1)|' is an abbreviation for `|app2(pp);
reduce(pp,2,math,-1)|'.

The code below is an exact translation of the production rules into \PASCAL,
using such macros, and the reader should have no difficulty understanding
the format by comparing the code with the symbolic productions as they
were listed earlier.

{\sl Caution:\/} The macros |app|, |app1|, |app2|, |app3|, |reduce|, 
and |freeze_text|, which is defined later, are sequences
of statements that are not enclosed with |begin| and $|end|$, because such
delimiters would make the \PASCAL\ program much longer. This means that
|begin| and |end| must be supplied when such a macro is used as a
single statement. Several mysterious bugs in the original programming
of \.{WEAVE} were caused by a failure to remember this fact. Next time
the author will know better. Note that |squash|, although similar to |reduce|,
is enclosed with |begin| and $|end|$ since it is usually found in situations
where this enclosure is required.

@d production(#)==debug prod(#) gubed; goto found; end
@d ex_production(#)==debug prod(#) gubed; goto found
@d reduce(#)==red(#); ex_production
@d squash(#)==begin sq(#); production
@d app(#)==tok_mem[tok_ptr]←#; incr(tok_ptr) {this is like |app_tok|,
	but it doesn't test for overflow}
@d app1(#)==tok_mem[tok_ptr]←tok_flag+trans[#]; incr(tok_ptr)
@d app2(#)==app1(#);app1(#+1)
@d app3(#)==app2(#);app1(#+2)

@ Let us consider the big case statement for productions now, before looking
at its context. We want to design the program so that this case statement
works, so we might as well not keep ourselves in suspense about exactly what
code needs to be provided with a proper environment.

@<Match a production at |pp| and |goto found|, if possible@>=
case cat[pp] of
alpha: @<Cases for |alpha|@>;
beginning: @<Cases for |beginning|@>;
case_head: @<Cases for |case_head|@>;
casey: @<Cases for |casey|@>;
clause: @<Cases for |clause|@>;
cond: @<Cases for |cond|@>;
elsie: @<Cases for |elsie|@>;
exp: @<Cases for |exp|@>;
intro: @<Cases for |intro|@>;
math: @<Cases for |math|@>;
mod_scrap: @<Cases for |mod_scrap|@>;
open: @<Cases for |open|@>;
proc: @<Cases for |proc|@>;
record_head: @<Cases for |record_head|@>;
semi: @<Cases for |semi|@>;
simp: @<Cases for |simp|@>;
stmt: @<Cases for |stmt|@>;
terminator: @<Cases for |terminator|@>;
var_head: @<Cases for |var_head|@>;
othercases do_nothing
endcases

@ @<Cases for |alpha|@>=
if cat[pp+1]=math then
	begin if cat[pp+2]=colon then squash(pp+1,2,math,0)(1)
	else if cat[pp+2]=omega then
		begin app1(pp); app(" "); app("$"); app1(pp+1);
		app("$"); app(" "); app(indent); app1(pp+2);
		reduce(pp,3,clause,-1)(2);
		end;
	end
else if cat[pp+1]=omega then
	begin app1(pp); app(" "); app(indent); app1(pp+1);
	reduce(pp,2,clause,-1)(3);
	end
else if cat[pp+1]=simp then squash(pp+1,1,math,0)(4)

@ @<Cases for |beginning|@>=
if cat[pp+1]=close then
	begin if (cat[pp+2]=terminator)∨(cat[pp+2]=stmt) then
		squash(pp,3,stmt,-2)(5);
	end
else if cat[pp+1]=stmt then
	begin app1(pp); app(break); app1(pp+1); reduce(pp,2,beginning,0)(6);
	end

@ @<Cases for |case_head|@>=
if cat[pp+1]=casey then
	begin if cat[pp+2]=clause then
		begin app1(pp); app(outdent); app2(pp+1);
		reduce(pp,3,case_head,0)(7);
		end;
	end
else if cat[pp+1]=close then
	begin if cat[pp+2]=terminator then
		begin app1(pp); app(cancel); app(outdent); app2(pp+1);
		reduce(pp,3,stmt,-2)(8);
		end;
	end
else if cat[pp+1]=stmt then
	begin app1(pp); app(force); app1(pp+1); reduce(pp,2,case_head,0)(9);
	end

@ @<Cases for |casey|@>=
if cat[pp+1]=clause then squash(pp,2,case_head,0)(10)

@ @<Cases for |clause|@>=
if cat[pp+1]=stmt then
	begin app1(pp); app(break); app1(pp+1); app(cancel); app(outdent);
	app(force); reduce(pp,2,stmt,-2)(11);
	end

@ @<Cases for |cond|@>=
if (cat[pp+1]=clause)∧(cat[pp+2]=stmt) then
	if cat[pp+3]=elsie then
		begin app2(pp); app(break); app2(pp+2); app(" ");
		app(cancel); reduce(pp,4,clause,-2)(12);
		end
	else	begin app2(pp); app(break); app1(pp+2); app(cancel);
		app(outdent); app(force); reduce(pp,3,stmt,-2)(13);
		end
		
@ @<Cases for |elsie|@>=
squash(pp,1,intro,-3)(14)

@ @<Cases for |exp|@>=
if cat[pp+1]=math then
	begin if cat[pp+2]=simp then
		begin app3(pp); app("}"); reduce(pp,3,math,-1)(15);
		end;
	end
else if cat[pp+1]=simp then
	begin app2(pp); app("}"); reduce(pp,2,math,-1)(16);
	end

@ @<Cases for |intro|@>=
if cat[pp+1]=stmt then
	begin app1(pp); app(" "); app(opt); app("7");
	app(cancel); app1(pp+1); reduce(pp,2,stmt,-2)(17);
	end

@ @<Cases for |math|@>=
if cat[pp+1]=colon then
	begin app(force); app(backup); app("$"); app1(pp);
	app("$"); app1(pp+1); reduce(pp,2,intro,-3)(18);
	end
else if cat[pp+1]=math then squash(pp,2,math,-1)(19)
else if cat[pp+1]=simp then squash(pp,2,math,-1)(20)
else if cat[pp+1]=terminator then
	begin app("$"); app1(pp); app("$"); app1(pp+1);
	reduce(pp,2,stmt,-2)(21);
	end

@ @<Cases for |mod_scrap|@>=
if (cat[pp+1]=terminator)∨(cat[pp+1]=semi) then
	begin app2(pp); app(force); reduce(pp,2,stmt,-2)(22);
	end
else squash(pp,1,simp,-2)(23)

@ @<Cases for |open|@>=
if cat[pp+1]=casey then
	begin app1(pp); app(cancel); app1(pp+1); reduce(pp,2,casey,-2)(24);
	end
else if cat[pp+1]=close then
	begin app1(pp); app("\"); app(","); app1(pp+1);
	reduce(pp,2,math,-1)(25);
	end
else if cat[pp+1]=math then @<Cases for |open@,math|@>
else if cat[pp+1]=proc then
	begin if cat[pp+2]=intro then
		begin app(math_op); app(cancel); app1(pp+1); app("}");
		reduce(pp+1,2,math,0)(32);
		end;
	end
else if cat[pp+1]=simp then squash(pp+1,1,math,0)(33)
else if cat[pp+1]=var_head then
	begin if cat[pp+2]=intro then
		begin app(math_op); app(cancel); app1(pp+1); app("}");
		reduce(pp+1,2,math,0)(34);
		end;
	end

@ @<Cases for |open@,math|@>=
begin if cat[pp+2]=casey then squash(pp,3,casey,-2)(26)
else if cat[pp+2]=close then squash(pp,3,math,-1)(27)
else if cat[pp+2]=colon then squash(pp+1,2,math,0)(28)
else if cat[pp+2]=proc then
	begin if cat[pp+3]=intro then
		begin app1(pp+1); app(math_op); app(cancel);
		app1(pp+2); app("}"); reduce(pp+1,3,math,0)(29);
		end;
	end
else if cat[pp+2]=semi then
	begin app2(pp+1); app("\"); app(","); app(opt); app("5");
	reduce(pp+1,2,math,0)(30);
	end
else if cat[pp+2]=var_head then
	begin if cat[pp+3]=intro then
		begin app1(pp+1); app(math_op); app(cancel);
		app1(pp+2); app("}"); reduce(pp+1,3,math,0)(31);
		end;
	end;
end

@ @<Cases for |proc|@>=
if cat[pp+1]=beginning then
	begin if (cat[pp+2]=close)∧(cat[pp+3]=terminator) then
		begin app1(pp); app(cancel); app(outdent); app3(pp+1);
		reduce(pp,4,stmt,-2)(35);
		end;
	end
else if cat[pp+1]=stmt then
	begin app1(pp); app(break); app1(pp+1);
	reduce(pp,2,proc,-2)(36);
	end

@ @<Cases for |record_head|@>=
if (cat[pp+1]=intro)∧(cat[pp+2]=casey) then
	begin app2(pp); app(" "); app(cancel); app1(pp+2);
	reduce(pp,3,casey,-2)(37);
	end
else	begin app(indent); app1(pp); app(cancel);
	reduce(pp,1,case_head,0)(38);
	end

@ @<Cases for |semi|@>=
squash(pp,1,terminator,-3)(39)

@ @<Cases for |simp|@>=
if cat[pp+1]=colon then
	begin app(force); app(backup); app2(pp); reduce(pp,2,intro,-3)(40);
	end
else if cat[pp+1]=math then squash(pp,2,math,-1)(41)
else if cat[pp+1]=mod_scrap then squash(pp,2,mod_scrap,0)(42)
else if cat[pp+1]=simp then squash(pp,2,simp,-2)(43)
else if cat[pp+1]=terminator then squash(pp,2,stmt,-2)(44)

@ @<Cases for |stmt|@>=
if cat[pp+1]=stmt then
	begin app1(pp); app(break); app1(pp+1);
	reduce(pp,2,stmt,-2)(45);
	end

@ @<Cases for |terminator|@>=
squash(pp,1,stmt,-2)(46)

@ @<Cases for |var_head|@>=
if cat[pp+1]=beginning then squash(pp,1,stmt,-2)(47)
else if cat[pp+1]=math then
	begin if cat[pp+2]=colon then
		begin app("$"); app1(pp+1); app("$"); app1(pp+2);
		reduce(pp+1,2,intro,+1)(48);
		end;
	end
else if cat[pp+1]=simp then
	begin if cat[pp+2]=colon then squash(pp+1,2,intro,+1)(49);
	end
else if cat[pp+1]=stmt then
	begin app1(pp); app(break); app1(pp+1); reduce(pp,2,var_head,-2)(50);
	end

@ The `|freeze_text|' macro is used to give official status to a token list.
Before saying |freeze_text|, items are appended to the current token list,
and we know that the eventual number of this token list will be the current
value of |text_ptr|. But no list of that number really exists as yet,
because no ending point for the current list has been
stored in the |tok_start| array. After saying |freeze_text|, the
old current token list becomes legitimate, and its number is the current
value of |text_ptr-1| since |text_ptr| has been increased. The new
current token list is empty and ready to be appended to.
Note that |freeze_text| does not check to see that |text_ptr| hasn't gotten
too large, since it is assumed that this test was done beforehand. Also
note that |freeze_text| is not enclosed in |begin| and $|end|$ so the 
caution, as mentioned above, must be observed.

@d freeze_text==incr(text_ptr); tok_start[text_ptr]←tok_ptr

@ The `|reduce|' macro used in our code for productions actually calls on a
procedure named `|red|', which makes the appropriate changes to the scrap list.

@p procedure red(j:sixteen_bits; k:eight_bits; c:eight_bits; d:integer);
var i:0..max_scraps; {index into scrap memory}
begin cat[j]←c; trans[j]←text_ptr; freeze_text;
if k>1 then
	begin for i←j+k to lo_ptr do
		begin cat[i-k+1]←cat[i]; trans[i-k+1]←trans[i];
		end;
	lo_ptr←lo_ptr-k+1;
	end;
@<Change |pp| to $\max(|scrap_base,pp+d|)$@>;
end;

@ @<Change |pp| to $\max(|scrap_base,pp+d|)$@>=
if pp+d≥scrap_base then pp←pp+d
else pp←scrap_base

@ Similarly, the `|squash|' macro invokes a procedure called `|sq|'. This
procedure takes advantage of the simplification that occurs when |k=1|.

@p procedure sq(j:sixteen_bits; k:eight_bits; c:eight_bits; d:integer);
var i:0..max_scraps; {index into scrap memory}
begin if k=1 then
	begin cat[j]←c; @<Change |pp|...@>;
	end
else	begin for i←j to j+k-1 do
		begin app1(i);
		end;
	red(j,k,c,d);
	end;
end;

@ Here now is the code that applies productions as long as possible. It requires
two local labels (|found| and |done|), as well as a local variable (|i|).

@<Reduce the scraps using the productions until no more rules apply@>=
loop begin @<Make sure the entries |cat[pp..(pp+3)]| are defined@>;
	if (tok_ptr+8>max_toks)∨(text_ptr+4>max_texts) then
		overflow('token');
	if pp>lo_ptr then goto done;
	@<Match a production...@>;
	incr(pp); {if no match was found, we move to the right}
	found:end;
done:

@ If we get to the end of the scrap list, category codes equal to zero are
stored, since zero does not match anything in a production.

@<Make sure the entries...@>=
if lo_ptr<pp+3 then
	begin repeat if hi_ptr≤scrap_ptr then
		begin incr(lo_ptr);@/
		cat[lo_ptr]←cat[hi_ptr]; trans[lo_ptr]←trans[hi_ptr];@/
		incr(hi_ptr);
		end;
	until (hi_ptr>scrap_ptr)∨(lo_ptr=pp+3);
	for i←lo_ptr+1 to pp+3 do cat[i]←0;
	end

@ If \.{WEAVE} is being run in debugging mode, the production numbers and
current stack categories will be printed out when |tracing| is set |true|.

@<Glo...@>=
debug@!tracing:boolean; {can be used to show parsing details}
gubed

@ @p debug procedure prod(n:eight_bits); {shows current categories}
var k:1..max_scraps; {index into |cat|}
begin if tracing then
	begin ex_print_nl(n:0,':');
	for k←scrap_base to lo_ptr do
		begin if k=pp then print('*') @+ else print(' ');
		print_cat(cat[k]);
		end;
	if hi_ptr≤scrap_ptr then print('...'); {indicate that more is coming}
	end;
end;
gubed

@ The |translate| function assumes that scraps have been stored in
positions |scrap_base| through |scrap_ptr| of |cat| and |trans|. It
appends a |terminator| scrap and begins to apply productions as much as
possible. The result is a token list containing the concatenation of the
translations of all remaining scraps, separated by blank spaces, with
dollar signs surrounding the translations of |math| scraps. After calling
|translate|, we will have |text_ptr+3≤max_texts| and |tok_ptr+6≤max_toks|,
so it will be possible to create up to three token lists with up to six
tokens without checking for overflow. Before calling |translate|, we should
have |text_ptr<max_texts| and |scrap_ptr<max_scraps|, since |translate| might
add a new text and a new scrap before it checks for overflow.

@p function translate:text_pointer; {converts a sequence of scraps}
label done,found;
var i: 1..max_scraps; {index into |cat|}
k:0..long_buf_size; {index into |buffer|}
begin pp←scrap_base; lo_ptr←pp-1; hi_ptr←pp;
@<If tracing, print an indication of where we are@>;
@<Reduce the scraps...@>;
if (lo_ptr=scrap_base)∧(cat[lo_ptr]≠math) then translate←trans[lo_ptr]
else	begin for pp←scrap_base to lo_ptr do
		begin if pp≠scrap_base then
			begin app(" ");
			end;
		if cat[pp]=math then
			begin app("$");
			end;
		app1(pp);
		if cat[pp]=math then
			begin app("$");
			end;
		if tok_ptr+6>max_toks then overflow('token');
		end;
	freeze_text; translate←text_ptr-1;
	end;
end;

@ @<If tracing,...@>=
debug if tracing then
	begin ex_print_nl('Tracing after p.',page:0,',l.',line:0,':');
	if loc>50 then
		begin print('...');
		for k←loc-50 to loc do print(chr(buffer[k-1]));
		end
	else for k←1 to loc do print(chr(buffer[k-1]));
	end
gubed
@* Initializing the scraps.
If we are going to use the powerful production mechanism just developed, we
must get the scraps set up in the first place, given a \PASCAL\ text. A table
of the initial scraps corresponding to \PASCAL\ tokens appeared above in the
section on parsing; our goal now is to implement that table. We shall do this
by implementing a subroutine called |PASCAL_parse| that is analogous to the
|PASCAL_xref| routine used during phase one.

Like |PASCAL_xref|, the |PASCAL_parse| procedure starts with the current value
of |next_control| and it uses the operation |next_control←get_next| repeatedly
to read \PASCAL\ text until encountering the next `\v' or `\.\{', or until
|next_control≥format|. The scraps corresponding to what it reads are
appended into the |cat| and |trans| arrays, and |scrap_ptr| is advanced.

After studying |PASCAL_parse|, we will look at the sub-procedure |app_comment|
that it uses in one of its branches.

@p @<Declaration of the |app_comment| procedure@>;
procedure PASCAL_parse; {creates scraps from \PASCAL\ tokens}
label reswitch, exit;
var j:0..long_buf_size; {index into |buffer|}
@!p:name_pointer; {identifier designator}
begin while next_control<format do
	begin @<Append the scrap appropriate to |next_control|@>;
	next_control←get_next;
	if (next_control="|")∨(next_control="{") then return;
	end;
exit:end;

@ The macros defined here are helpful abbreviations for the operations needed
when generating the scraps. A scrap of category $c$ whose translation has three
tokens $t↓1$, $t↓2$, $t↓3$ is generated by |sc3|$(t↓1)(t↓2)(t↓3)$, etc.

@d s0(#)==incr(scrap_ptr); cat[scrap_ptr]←#; trans[scrap_ptr]←text_ptr;
	freeze_text;
	end
@d s1(#)==app(#);s0
@d s2(#)==app(#);s1
@d s3(#)==app(#);s2
@d s4(#)==app(#);s3
@d sc4==begin s4
@d sc3==begin s3
@d sc2==begin s2
@d sc1==begin s1
@d sc0(#)==begin incr(scrap_ptr); cat[scrap_ptr]←#; trans[scrap_ptr]←0;
	end
@d comment_scrap(#)==begin app(#); app_comment;
	end

@ @<Append the scr...@>=
if (scrap_ptr+4>max_scraps)∨(tok_ptr+6>max_toks)∨(text_ptr+4>max_texts) then
	overflow('scrap');
reswitch: case next_control of
set_element_sign: sc3("\")("i")("n")(math);
double_dot: sc3("\")("t")("o")(math);
string: @<Append a string scrap@>;
"#","$","%","↑": sc2("\")(next_control)(math);
ignore,"|",xref_roman,xref_typewriter: do_nothing;
"(","[": sc1(next_control)(open);
")","]": sc1(next_control)(close);
"*": sc4("\")("a")("s")("t")(math);
",": sc3(",")(opt)("9")(math);
".","0","1","2","3","4","5","6","7","8","9": sc1(next_control)(simp);
";": sc1(";")(semi);
":": sc1(":")(colon);
identifier: @<Append an identifier scrap@>;
exponent: sc3("\")("E")("{")(exp);
begin_comment: sc2("\")("B")(math);
end_comment: sc2("\")("T")(math);
octal: sc2("\")("O")(simp);
thin_space: sc2("\")(",")(math);
TEX_string: @<Append a \TEX\ string scrap@>;
line_break: comment_scrap(force);
big_line_break: comment_scrap(big_force);
no_line_break: begin app(big_cancel); app("\"); app(" ");
	comment_scrap(big_cancel);
	end;
pseudo_semi: sc0(semi);
join: sc2("\")("J")(math);
othercases sc1(next_control)(math)
endcases

@ The following code must use |app_tok| instead of |app| in order to
protect against overflow. Note that |tok_ptr+1≤max_toks| after |app_tok|
has been used, so another |app| is legitimate before testing again.
Many of the special characters in a string must be prefixed by `\.\\' so that
\TEX\ will print them properly.

@<Append a string scrap@>=
begin app("\"); app("."); app("{"); j←id_first;
while j<id_loc do
	begin case buffer[j] of
	" ","\","#","%","$","↑","'","`","↓","{","}","⊗",not_equal,
		greater_or_equal,less_or_equal: begin app("\");
			end;
	"@@": if buffer[j+1]="@@" then incr(j)
		else err_print('! Double @@ should be used in strings');
	othercases do_nothing
	endcases;
	ex_app_tok(buffer[j]); incr(j);
	end;
sc1("}")(simp);
end

@ @<Append a \TEX\ string scrap@>=
begin app("\"); app("h"); app("b"); app("o"); app("x");
app("{");
for j←id_first to id_loc-1 do app_tok(buffer[j]);
sc1("}")(simp);
end

@ @<Append an identifier scrap@>=
begin p←id_lookup(normal);
case ilk[p] of
normal: sc1(id_flag+p)(simp); {not a reserved word}
array_like: sc1(res_flag+p)(alpha); {\&{array}, \&{file}, \&{set}}
const_like: sc3(force)(backup)(res_flag+p)(intro); {\&{const}, \&{label}, \&{type}}
div_like: sc3(math_bin)(res_flag+p)("}")(math); {\&{div}, \&{mod}}
do_like: sc1(res_flag+p)(omega); {\&{do}, \&{of}, \&{then}}
for_like: sc2(force)(res_flag+p)(alpha); {\&{for}, \&{while}, \&{with}}
goto_like: sc1(res_flag+p)(intro); {\&{goto}, \&{packed}}
nil_like: sc1(res_flag+p)(simp); {\&{nil}}
loop_like: sc3(force)(res_flag+p)(indent)(clause); {\&{xclause}}
to_like: sc3(math_rel)(res_flag+p)("}")(math); {\&{downto}, \&{to}}
@<Cases that generate more than one scrap@>
othercases begin next_control←ilk[p]-char_like; goto reswitch;
	end {\&{and}, \&{in}, \&{not}, \&{or}}
endcases;
end

@ @<Cases that generate more than one scrap@>=
begin_like: begin sc3(force)(res_flag+p)(cancel)(beginning); sc0(intro);
	end; {\&{begin}}
case_like: begin sc0(casey); sc2(force)(res_flag+p)(alpha);
	end; {\&{case}}
else_like: begin @<Append |terminator| if not already present@>;
	sc3(force)(backup)(res_flag+p)(elsie);
	end; {\&{else}}
end_like: begin @<Append |term...@>;
	sc2(force)(res_flag+p)(close);
	end; {\&{end}}
if_like: begin sc0(cond); sc2(force)(res_flag+p)(alpha);
	end; {\&{if}}
proc_like: begin sc4(force)(backup)(res_flag+p)(cancel)(proc);
	sc3(indent)("\")(" ")(intro);
	end; {\&{function}, \&{procedure}, \&{program}}
record_like: begin sc1(res_flag+p)(record_head); sc0(intro);
	end; {\&{record}}
repeat_like: begin sc4(force)(indent)(res_flag+p)(cancel)(beginning);
	sc0(intro);
	end; {\&{repeat}}
until_like: begin @<Append |term...@>;
	sc3(force)(backup)(res_flag+p)(close); sc0(clause);
	end; {\&{until}}
var_like: begin sc4(force)(backup)(res_flag+p)(cancel)(var_head); sc0(intro);
	end; {\&{var}}

@ If a comment or semicolon appears before the reserved words \&{end}, \&{else},
or \&{until}, the |semi| or |terminator| scrap that is already present overrides
the |terminator| scrap belonging to this reserved word.

@<Append |termin...@>=
if (scrap_ptr<scrap_base)∨((cat[scrap_ptr]≠terminator)∧
		(cat[scrap_ptr]≠semi)) then sc0(terminator)

@ A comment is incorporated into the previous scrap if that scrap is of type
|omega| or |semi| or |terminator|. (These three categories have consecutive
category codes.) Otherwise the comment is entered as a separate scrap
of type |terminator|, and it will combine with a |terminator| scrap that
immediately follows it.

The |app_comment| procedure takes care of placing a comment at the end of the
current scrap list. When |app_comment| is called, we assume that the current
token list is the translation of the comment involved.

@<Declaration of the |app_comment|...@>=
procedure app_comment; {append a comment to the scrap list}
begin freeze_text;
if (scrap_ptr<scrap_base)∨(cat[scrap_ptr]<omega)∨
		(cat[scrap_ptr]>terminator) then sc0(terminator)
else	begin app1(scrap_ptr); {|omega| or |semi| or |terminator|}
	end;
app(text_ptr-1+tok_flag); trans[scrap_ptr]←text_ptr; freeze_text;
end

@ When the `\v' that introduces \PASCAL\ text is sensed, a call on
|PASCAL_translate| will return a pointer to the \TEX\ translation of
that text. If scraps exist in the |cat| and |trans| arrays, they are
unaffected by this translation process.

@p function PASCAL_translate: text_pointer;
var p:text_pointer; {points to the translation}
@!save_base:0..max_scraps; {holds original value of |scrap_base|}
begin save_base←scrap_base; scrap_base←scrap_ptr+1;
PASCAL_parse; {get the scraps together}
if next_control≠"|" then err_print('! Missing "|" after PASCAL text');
ex_app_tok(cancel); app_comment; {place a |cancel| token as a final ``comment''}
p←translate; {make the translation}
stat if scrap_ptr>max_scr_ptr then max_scr_ptr←scrap_ptr;
tats
scrap_ptr←scrap_base-1; scrap_base←save_base; {scrap the scraps}
PASCAL_translate←p;
end;

@ The |outer_parse| routine is to |PASCAL_parse| as |outer_xref|
is to |PASCAL_xref|: It constructs a sequence of scraps for \PASCAL\ text
until |next_control≥format|. Thus, it takes care of embedded comments.

@p procedure outer_parse; {makes scraps from \PASCAL\ tokens and comments}
var bal:eight_bits; {brace level in comment}
@!p,@!q:text_pointer; {partial comments}
begin while next_control<format do
	if next_control≠"{" then PASCAL_parse
	else	begin if (tok_ptr+7>max_toks)∨(text_ptr+3>max_texts)∨
			(scrap_ptr≥max_scraps) then overflow('token/scrap');
		app("\"); app("C"); app("{");
		bal←copy_comment(1); next_control←"|";
		while bal>0 do
			begin p←text_ptr; freeze_text; q←PASCAL_translate;
			{at this point we have |tok_ptr+6≤max_toks|}
			app(tok_flag+p); app(inner_tok_flag+q);
			if next_control="|" then bal←copy_comment(bal)
			else bal←0; {an error has been reported}
			end;
		app(force); app_comment; {the full comment becomes a scrap}
		end;
end;
@* Output of tokens.
So far our programs have only built up multi-layered token lists in \.{WEAVE}'s
internal memory; we have to figure out how to get them into the desired final
form. The job of converting token lists to characters in the \TEX\ output file
is not difficult, although it is an implicitly recursive process. Three main
considered had to be kept in mind when this part of \.{WEAVE} was designed:
(a) There are two modes of output, |outer| mode that translates tokens like
|force| into line-breaking control sequences, and |inner| mode that ignores
them except that blank spaces take the place of line breaks. (b) The |cancel|
instruction applies to adjacent token or tokens that are output, and this
cuts across levels of recursion since `|cancel|' occurs at the beginning or end
of a token list on one level. (c) The \TEX\ output file will be semi-readable
if line breaks are inserted after the result of tokens like |break| and |force|.
(d) The final line break should be suppressed, and there should be no |force|
token output immediately after `\.{\\Y\\P}'.

@ The output process uses a stack to keep track of what is going on at
different ``levels'' as the token lists are being written out. Entries on
this stack have three parts:

\yskip\hang |end_field| is the |tok_mem| location where the token list of a
particular level will end;

\yskip\hang |tok_field| is the |tok_mem| location from which the next token
on a particular level will be read;

\yskip\hang |mode_field| is the current mode, either |inner| or |outer|.

\yskip\noindent The current values of these quantities are referred to
quite frequently, so they are stored in a separate place instead of in the
|stack| array. We call the current values |cur_end|, |cur_tok|, and
|cur_mode|.

The global variable |stack_ptr| tells how many levels of output are
currently in progress. The end of output occurs when an |end_translation|
token is found, so the stack is never empty except when we first begin the
output process.

@<Types...@>=
@!mode=(inner,outer);
@!output_state=record@!end_field:sixteen_bits; {ending location of token list}
	@!tok_field:sixteen_bits; {present location within token list}
	@!mode_field:mode; {interpretation of control tokens}
	end;

@ @d cur_end==cur_state.end_field {current ending location in |tok_mem|}
@d cur_tok==cur_state.tok_field {location of next output token in |tok_mem|}
@d cur_mode==cur_state.mode_field {current mode of interpretation}
@d init_stack==stack_ptr←0;cur_mode←outer {do this to initialize the stack}

@<Glob...@>=
@!cur_state:output_state; {|cur_end|, |cur_tok|, |cur_mode|}
@!stack:array[1..stack_size] of output_state; {info for non-current levels}
@!stack_ptr:0..stack_size; {first unused location in the output state stack}
stat@!max_stack_ptr:0..stack_size; {largest value assumed by |stack_ptr|}
tats

@ @<Set init...@>=stat max_stack_ptr←0;@+tats

@ To insert token-list $p$ into the output, the |push_level| subroutine
is called; it saves the old level of output and gets a new one going.
The value of |cur_mode| is not changed.

@p procedure push_level(p:text_pointer); {suspends the current level}
begin if stack_ptr=stack_size then overflow('stack')
else	begin if stack_ptr>0 then
		stack[stack_ptr]←cur_state; {save |cur_end|$\ldotsm$|cur_mode|}
	incr(stack_ptr);
	stat if stack_ptr>max_stack_ptr then max_stack_ptr←stack_ptr;@+tats
	cur_tok←tok_start[p]; cur_end←tok_start[p+1];
	end;
end;

@ Conversely, the |pop_level| routine restores the conditions that were in force
when the current level was begun. This subroutine will never be called when
|stack_ptr=1|. It is so simple, we declare it as a macro:

@d pop_level==begin decr(stack_ptr); cur_state←stack[stack_ptr];
	end {do this when |cur_tok| reaches |cur_end|}

@ The |get_output| function returns the next byte of output that is not a
reference to a token list. It returns the values |identifier| or |res_word|
or |mod_name| if the next token is to be an identifier (typeset in
italics), a reserved word (typeset in boldface) or a module name (typeset
by a complex routine that might generate additional levels of output).
In these cases |cur_name| points to the identifier or module name in
question.

@d res_word=@'201 {returned by |get_output| for reserved words}
@d mod_name=@'200 {returned by |get_output| for module names}

@p function get_output:eight_bits; {returns the next token of output}
label restart;
var a:sixteen_bits; {current item read from |tok_mem|}
begin restart: while cur_tok=cur_end do pop_level;
a←tok_mem[cur_tok]; incr(cur_tok);
if a≥@'400 then
	begin cur_name←a mod id_flag;
	case a div id_flag of
	2: a←res_word; {|a=res_flag+cur_name|}
	3: a←mod_name; {|a=mod_flag+cur_name|}
	4: begin push_level(cur_name); goto restart;
		end; {|a=tok_flag+cur_name|}
	5: begin push_level(cur_name); cur_mode←inner; goto restart;
		end; {|a=inner_tok_flag+cur_name|}
	othercases a←identifier {|a=id_flag+cur_name|}
	endcases;
	end;
debug if trouble_shooting then debug_help; @+ gubed
get_output←a;
end;

@ The real work associated with token output is done by |make_output|,
which repeatedly calls |get_output| and feeds characters to the output
buffer until an |end_translation| token is sensed. This procedure can
be called recursively, since a module name may include embedded \PASCAL\
text; however, the depth of recursion never exceeds one level, since
module names cannot be inside of module names.

A procedure called |output_PASCAL| does the scanning, translation, and output
of \PASCAL\ text within `\pb' brackets,
 and this procedure uses |make_output| to output
the current token list. The recursive call of |make_output| actually
occurs when |make_output| calls |output_PASCAL| while outputting the
name of a module. 
@↑recursion@>

@p procedure make_output; forward;
@#
procedure output_PASCAL; {outputs the current token list}
var save_tok_ptr,@!save_text_ptr,@!save_next_control:sixteen_bits; 
	{values to be restored}
p:text_pointer; {translation of the \PASCAL\ text}
begin save_tok_ptr←tok_ptr; save_text_ptr←text_ptr;
save_next_control←next_control; next_control←"|"; p←PASCAL_translate;
app(p+inner_tok_flag); app(end_translation); {append a sentinel}
freeze_text; push_level(text_ptr-1); make_output; {output the list}
stat if text_ptr>max_txt_ptr then max_txt_ptr←text_ptr;
if tok_ptr>max_tok_ptr then max_tok_ptr←tok_ptr;
tats
text_ptr←save_text_ptr; tok_ptr←save_tok_ptr; {forget the tokens}
next_control←save_next_control; {restore |next_control| to original state}
end;

@ @p procedure make_output; {outputs the equivalents of tokens}
label reswitch,exit,found;
var a:eight_bits; {current output byte}
@!b:eight_bits; {next output byte}
@!k,@!k_limit:0..max_bytes; {indices into |byte_mem|}
@!j:0..long_buf_size; {index into |buffer|}
@!string_delimiter:ascii_code; {first and last character of string being copied}
@!save_loc,@!save_limit:0..long_buf_size; {|loc| and |limit| to be restored}
begin loop begin a←get_output;
reswitch: case a of
	end_translation: return;
	identifier,res_word:@<Output an identifier@>;
	mod_name:@<Output a module name@>;
	math_bin,math_op,math_rel:@<Output a \.{\\math} operator@>;
	cancel: begin repeat a←get_output;
		until (a<backup)∨(a>big_force);
		goto reswitch;
		end;
	big_cancel: begin repeat a←get_output;
		until ((a<backup)∧(a≠" "))∨(a>big_force);
		goto reswitch;
		end;
	indent,outdent,opt,backup,break,force,big_force:@<Output a control,
		look ahead in case of line breaks, possibly |goto reswitch|@>;
	othercases out(a) {otherwise $a$ is an ascii character}
	endcases;
	end;
exit:end;

@ An identifier of length one does not have to be enclosed in braces. Thus
we output `\.{\\\\a}' but `\.{\\\\\{aa\}}'.

@<Output an identifier@>=
begin out("\");
if a=identifier then out("\")
else out("&"); {|a=res_word|}
if byte_start[cur_name+1]=byte_start[cur_name]+1 then
	out(byte_mem[byte_start[cur_name]])
else out_name(cur_name);
end

@ @<Output a \...@>=
begin out5("\")("m")("a")("t")("h");
if a=math_bin then out3("b")("i")("n")
else if a=math_rel then out3("r")("e")("l")
else out2("o")("p");
out("{");
end

@ The current mode does not affect the behavior of \.{WEAVE}'s output routine
except when we are outputting control tokens.

@<Output a control...@>=
if a<break then
	begin if cur_mode=outer then
		begin out2("\")(a+-cancel+"0");
		if a=opt then out(get_output) {|opt| is followed by a digit}
		end
	else if a=opt then b←get_output {ignore digit following |opt|}
	end
else @<Look ahead for strongest line break, |goto reswitch|@>

@ If several of the tokens |break|, |force|, |big_force| occur in a
row, possibly mixed with blank spaces (which are ignored),
the largest one is used. A line break also occurs in the output file,
except at the very end of the translation. The very first line break
is suppressed (i.e., a line break that follows `\.{\\Y\\P}').

@<Look ahead for st...@>=
begin b←a;
loop	begin a←get_output;
	if (a=cancel)∨(a=big_cancel) then goto reswitch;
		{|cancel| overrides everything}
	if ((a≠" ")∧(a<break))∨(a>big_force) then
		begin if cur_mode=outer then
			begin if out_ptr>3 then
				if (out_buf[out_ptr]="P")∧
					(out_buf[out_ptr-1]="\")∧
					(out_buf[out_ptr-2]="Y")∧
					(out_buf[out_ptr-3]="\") then
					goto reswitch;
			out2("\")(b-cancel+"0");
			if a≠end_translation then finish_line;
			end
		else if a≠end_translation then out(" ");
		goto reswitch;
		end;
	if a>b then b←a; {if |a=" "| we have |a<b|}
	end;
end

@ The remaining part of |make_output| is somewhat more complicated. When we
output a module name, we may need to enter the parsing and translation
routines, since the name may contain \PASCAL\ code embedded in \pb\ 
constructions. This \PASCAL\ code is placed at the end of the active
input buffer and the translation process uses the end of the active
|tok_mem| area.

@<Output a module name@>=
begin out2("\")("X");
if num(xref[cur_name])≥def_flag then out_val(num(xref[cur_name])-def_flag)
else out("0"); {output the module number, or zero if it was undefined}
out(":"); @<Output the text of the module name@>;
out2("\")("X");
end

@ @<Output the text...@>=
k←byte_start[cur_name]; k_limit←byte_start[cur_name+1];
while k<k_limit do
	begin b←byte_mem[k]; incr(k);
	if b="@@" then @<Skip next character, give error if not \.{@@}@>;
	if b≠"|" then out(b)
	else	begin @<Copy the \PASCAL\ text into |buffer[(limit+1)..j]|@>;
		save_loc←loc; save_limit←limit; loc←limit+2; limit←j+1;
		buffer[limit]←"|"; output_PASCAL; 
		loc←save_loc; limit←save_limit;
		end;
	end

@ @<Skip next char...@>=
begin if byte_mem[k]≠"@@" then
	begin ex_print_nl('! Illegal control code in module name:');
	ex_print_nl('<'); print_id(cur_name); print('> ');
	end;
incr(k);
end

@ The \PASCAL\ text enclosed in \pb\ should not contain `\v' characters,
except within strings. We put a `\v' at the front of the buffer, so that an
error message that displays the whole buffer will look a little bit sensible.
The variable |string_delimiter| is zero outside of strings, otherwise it
equals the delimiter that began the string being copied.

@<Copy the \PASCAL\ text into...@>=
j←limit+1; buffer[j]←"|"; string_delimiter←0;
loop	begin if k=k_limit then
		begin ex_print_nl('! PASCAL text in module name didn''t end:');
		ex_print_nl('<'); print_id(cur_name); print('> ');
		goto found;
		end;
	b←byte_mem[k]; incr(k);
	if (b="""")∨(b="'") then
		if string_delimiter=0 then string_delimiter←b
		else if string_delimiter=b then string_delimiter←0;
	if (b≠"|")∨(string_delimiter≠0) then
		begin if j>long_buf_size-3 then overflow('buffer');
		incr(j); buffer[j]←b;
		end
	else goto found;
	end;
found:
@* Phase two processing.
We have assembled enough pieces of the puzzle in order to be ready to specify
the processing in \.{WEAVE}'s main pass over the source file. Phase two
is analogous to phase one, except that more work is involved because we must
actually output the \TEX\ material instead of merely looking at the
\.{WEB} specifications.

@<Phase II: Read all the text again and translate it to \TEX\ form@>=
reset_input; ex_print_nl('Writing the output file...');
module_count←0;
repeat copy_limbo;
if ¬input_has_ended then
	begin repeat @<Translate the current module@>;
	until next_control=page_end;
	if ¬input_has_ended then write_end_of_page;
	end;
until input_has_ended;

@ The output file will contain the control sequence \.{\\Y} between non-null
sections of a module, e.g., between the \TEX\ and definition parts if both
are nonempty. This puts a little white space between the parts when they are
printed. However, we don't want \.{\\Y} to occur between two definitions
within a single module. The variables |out_line| or |out_ptr| will
change if a section is non-null, so the following macros `|save_position|'
and `|emit_space_if_needed|' are able to handle the situation:

@d save_position==save_line←out_line; save_place←out_ptr
@d emit_space_if_needed==if (save_line≠out_line)∨(save_place≠out_ptr) then
	out2("\")("Y")

@<Glo...@>=
@!save_line,@!save_place:sixteen_bits; {former values of |out_line,out_ptr|}

@ @<Translate the current module@>=
incr(module_count);
@<Output the code for the beginning of a new module@>;
save_position;
@<Translate the \TEX\ part of the current module@>;
@<Translate the definition part of the current module@>;
@<Translate the \PASCAL\ part of the current module@>;
@<Show cross references to this module@>;

@ Modules beginning with the \.{WEB} control sequence `\.{@@ }' start in the
output with the \TEX\ control sequence `\.{\\M}', followed by the module
number. Similarly, `\.{@@*}' modules lead to the control sequence `\.{\\N}'.

@<Output the code...@>=
ex_finish_line; flush_buffer(0); {insert a blank line, it looks nice}
out("\");
if buffer[loc-1]="*" then out("N") @+ else out("M");
out_val(module_count); out2(".")(" ")

@ In the \TEX\ part of a module, we simply copy the source text, except that
index entries are not copied and \PASCAL\ text within \pb\ is translated.

@<Translate the \T...@>=
repeat next_control←copy_TEX;
case next_control of
"|": begin init_stack; output_PASCAL;
	end;
xref_roman,xref_typewriter,module_name:
	begin loc←loc-2; next_control←get_next; {skip to \.{@@>}}
	end;
othercases do_nothing
endcases;
until next_control≥format

@ When we get to the following code we have |next_control≥format|, and
the token memory is in its initial empty state.

@<Translate the d...@>=
if next_control≤definition then {definition part non-empty}
	begin emit_space_if_needed; save_position;
	end;
while next_control≤definition do {|format| or |definition|}
	begin init_stack;
	if next_control=definition then @<Start a macro definition@>
	else @<Start a format definition@>;
	outer_parse; finish_PASCAL;
	end

@ The |finish_PASCAL| procedure outputs the translation of the current scraps,
preceded by the control sequence `\.{\\P}' and followed by the control sequence
`\.{\\par}'. It also restores the token and scrap memories to their initial
empty state.

A |force| token is appended to the current scraps before translation
takes place, so that the translation will normally end with \.{\\6} or
\.{\\7} (the \TEX\ macros for |force| and |big_force|). This \.{\\6} or
\.{\\7} is replaced by the concluding \.{\\par} or by \.{\\Y\\par}.

@p procedure finish_PASCAL; {finishes a definition or a \PASCAL\ part}
var p:text_pointer; {translation of the scraps}
begin out2("\")("P"); ex_app_tok(force); app_comment; p←translate;
app(p+tok_flag); app(end_translation); {the sentinel}
freeze_text; push_level(text_ptr-1); make_output; {output the list}
if out_ptr>1 then
	if out_buf[out_ptr-1]="\" then
		if out_buf[out_ptr]="6" then out_ptr←out_ptr-2
		else if out_buf[out_ptr]="7" then out_buf[out_ptr]←"Y";
out4("\")("p")("a")("r"); ex_finish_line;
stat if text_ptr>max_txt_ptr then max_txt_ptr←text_ptr;
if tok_ptr>max_tok_ptr then max_tok_ptr←tok_ptr;
if scrap_ptr>max_scr_ptr then max_scr_ptr←scrap_ptr;
tats
tok_ptr←1; text_ptr←1; scrap_ptr←0; {forget the tokens and the scraps}
end;

@ @<Start a macro...@>=
begin sc2("\")("D")(intro); {this will produce `\&{define }'}
next_control←get_next;
if next_control≠identifier then err_print('! Improper macro definition')
else sc1(id_flag+id_lookup(normal))(math);
next_control←get_next;
end

@ @<Start a format...@>=
begin sc2("\")("F")(intro); {this will produce `\&{format }'}
next_control←get_next;
if next_control=identifier then
	begin sc1(id_flag+id_lookup(normal))(math);
	next_control←get_next;
	if next_control=equivalence_sign then
		begin sc1(equivalence_sign)(math);
		next_control←get_next;
		if next_control=identifier then
			begin sc1(id_flag+id_lookup(normal))(math);
			sc0(semi); {insert an invisible semicolon}
			next_control←get_next;
			end;
		end;
	end;
if scrap_ptr≠5 then err_print('! Improper format definition');
end

@ Finally, when the \TEX\ and definition parts have been treated, we have
|next_control≥begin_pascal|. We will make the global variable |this_module|
point to the current module name, if it has a name.

@<Glob...@>=@!this_module:name_pointer; {the current module name, or zero}

@ @<Translate the \P...@>=
this_module←0;
if next_control≤module_name then
	begin emit_space_if_needed; init_stack;
	if next_control=begin_pascal then next_control←get_next
	else	begin this_module←cur_module;
		@<Check that |=| or |==| follows this module name, and
			emit the scraps to start the module definition@>;
		end;
	while next_control≤module_name do
		begin outer_parse;
		@<Emit the scrap for a module name if present@>;
		end;
	finish_PASCAL;
	end

@ @<Check that |=|...@>=
repeat next_control←get_next;
until next_control≠"+"; {allow optional `\.{+=}'}
if (next_control≠"=")∧(next_control≠equivalence_sign) then
	err_print('! You need an = sign after the module name')
else next_control←get_next;
if out_ptr>1 then
	if (out_buf[out_ptr]="Y")∧(out_buf[out_ptr-1]="\") then
		begin app(backup); {the module name will be flush left}
		end;
sc1(mod_flag+this_module)(mod_scrap);
cur_xref←xref[this_module];
if num(cur_xref)≠module_count+def_flag then
	begin sc3(math_rel)("+")("}")(math); {module name is multiply defined}
	this_module←0; {so we won't give cross-reference info here}
	end;
sc1(equivalence_sign)(math);
sc1(force)(semi); {this forces a line break unless `\.{@@+}' follows}

@ @<Emit the scrap...@>=
if next_control<module_name then
	begin ex_err_print('! You can''t do that in PASCAL text');
	next_control←get_next;
	end
else if next_control=module_name then
	begin sc1(mod_flag+cur_module)(mod_scrap); next_control←get_next;
	end

@ Cross references relating to a named module are given after the module
ends.

@<Show cross...@>=
if this_module>0 then
	begin cur_xref←xlink(cur_xref); {bypass current module number}
	if num(cur_xref)≥def_flag then
		begin footnote(def_flag); {`\.{See also...'}}
		cur_xref←xlink(cur_xref); {this will be the first reference
			to uses of this module}
		end;
	if cur_xref≠0 then footnote(0); {`\.{This code is used...'}}
	end

@ The |footnote| procedure gives cross reference information about
multiply defined module names (if its parameter is |def_flag|), or about
the uses of a module name (if its parameter is zero). It assumes that
|cur_xref| points to the first cross-reference entry of interest; however,
these entries are in the wrong order, so it makes the links point the
other way. Typical outputs: `\.{\\A\ section 101.}'; `\.{\\U\ sections 370
and 1009.}'; `\.{\\A\ sections 8, 27, and 64.}'.

@p procedure footnote(flag:sixteen_bits); {outputs module cross-references}
label done;
var p,@!q,@!r:0..max_refs; {cross-reference pointer variables}
begin ex_finish_line; out("\");
if flag=0 then out("U")@+else out("A");
out4(" ")("s")("e")("c"); out4("t")("i")("o")("n");
@<Invert the reference list and make $q$ point to its first element@>;
@<Output all the module numbers on the reference list@>;
out(".");
end;

@ The list inversion algorithm can be though of as inserting entries onto
a linked stack, with $q$ pointing to the head of the stack. A link $p$ is
regarded as null unless |num(p)>flag|; this works because |num(0)=0|.

@<Invert the ref...@>=
q←0; p←cur_xref;
repeat r←xlink(p); xlink(p)←q; q←p; p←r;
until num(p)≤flag;
xlink(cur_xref)←p; {if |flag=def_flag|, this plants the correct link}

@ The following code distinguishes three cases, ↓ccording as the number
of cross references is one, two, or more than two. Variable |q| points
to the first cross reference, and |cur_xref| points to the last.

@<Output all the module numbers...@>=
p←q; if p≠cur_xref then out("s"); {plural}
loop begin out(" "); out_val(num(p)-flag);
	if p=cur_xref then goto done;
	p←xlink(p); {$p$ points to the next cross reference to output}
	if (p≠cur_xref)∨(p≠xlink(q)) then out(","); {not the last of two}
	if p=cur_xref then out4(" ")("a")("n")("d"); {the last}
	end;
done:
@* Phase three processing.
We are nearly finished! \.{WEAVE}'s only remaining task is to write out the
index, after sorting the identifiers and index entries.

@<Phase III: Output the cross-reference index@>=
buffer[0]←" "; {this keeps |finish_line| from writing further page marks}
ex_print_nl('Writing the index...');
ex_finish_line; out4("\")("i")("n")("x"); ex_finish_line;
@<Do the first pass of sorting@>;
@<Sort and output the index@>;
out4("\")("f")("i")("n"); ex_finish_line;
print('Done.');

@ A left-to-right radix sorting method is used, since this makes it easy to
adjust the collating sequence and since the running time will be at worst
proportional to the total length of all entries in the index. We put the
identifiers into 102 different lists based on their first characters.
(Upper case letters are put into the same list as the corresponding lower
case letters, since we want to have `$d<\&{debug}<\&{do}$'.) The
list for character $c$ begins at location |bucket[c]| and continues through
the |link| array, since |link| is no longer needed for hash lists.

@<Glob...@>=
@!bucket:array[ascii_code] of name_pointer;
@!next_name: name_pointer; {successor of |cur_name| when sorting}
@!c:ascii_code; {index into |bucket|}
@!h:0..hash_size; {index into |hash|}

@ To begin the sorting, we go through all the hash lists and put each entry
having a nonempty cross-reference list into the proper bucket.

@<Do the first pass...@>=
for c←0 to 127 do bucket[c]←0;
for h←0 to hash_size-1 do
	begin next_name←hash[h];
	while next_name≠0 do
		begin cur_name←next_name; next_name←link[cur_name];
		if xref[cur_name]≠0 then
			begin c←byte_mem[byte_start[cur_name]];
			if (c≤"Z")∧(c≥"A") then c←c+@'40;
			link[cur_name]←bucket[c]; bucket[c]←cur_name;
			end;
		end;
	end

@ During the sorting phase we shall use the |cat| and |trans| arrays from
\.{WEAVE}'s parsing algorithm and rename them |depth| and |head|. They now
represent a stack of identifier lists for all the index entries that have
not yet been output. The variable |sort_ptr| tells haw many such lists are
present; the lists are output in reverse order (first |sort_ptr|, then
|sort_ptr-1|, etc.). The $j$th list starts at |head[j]|, and if the first
$k$ characters of all entries on this list are known to be equal we have
|depth[j]=k|.

@d depth==cat {reclaims memory that is no longer needed for parsing}
@d head==trans {ditto}
@d sort_ptr==scrap_ptr {ditto}
@d max_sorts==max_scraps {ditto}

@<Globals...@>=
@!cur_depth:eight_bits; {depth of current buckets}
@!cur_byte:0..max_bytes; {index into |byte_mem|}
@!cur_val:sixteen_bits; {current cross reference number}
stat@!max_sort_ptr:0..max_sorts;@+tats {largest value of |max_sorts|}

@ @<Set init...@>=stat max_sort_ptr←0;@+tats

@ The desired alphabetic order is specified by the |collate| array; namely,
|collate[0]<collate[1]<@t$\cdots$@><collate[101]|.

@<Glob...@>=@!collate:array[0..101] of ascii_code; {collation order}

@ We use the order $\hbox{null}<\.\ <\hbox{other characters}<\.\_<
\.A=\.a<\cdots<\.Z=\.z<\.0<\cdots<\.9.$
@↑system dependencies@>
The following code actually puts `\.\_' into two places of the |collate|
array, and omits code 127 (the ascii delete code), since this trick makes the
program work without change on systems that have `\.\_' in different code
positions.

@<Set init...@>=
collate[0]←0; collate[1]←" ";
for c←1 to " "-1 do collate[c+1]←c;
for c←" "+1 to "0"-1 do collate[c]←c;
for c←"9"+1 to "A"-1 do collate[c-10]←c;
for c←"Z"+1 to "a"-1 do collate[c-36]←c;
for c←"z"+1 to 126 do collate[c-62]←c;
collate[65]←"_";
for c←"a" to "z" do collate[c-"a"+66]←c;
for c←"0" to "9" do collate[c-"0"+92]←c;

@ Procedure |unbucket| goes through the buckets and adds nonempty lists
to the stack, using the collating sequence specified in the |collate| array.
The parameter to |unbucket| tells the current depth in the buckets.
Any two sequences that agree in their first 255 character positions are
regarded as identical.

@d infinity=255 {$\inf$ (approximately)}

@p procedure unbucket(d:eight_bits); {empties buckets having depth $d$}
var c:ascii_code; {index into |bucket|}
begin for c←101 downto 0 do if bucket[collate[c]]>0 then
	begin if sort_ptr>max_sorts then overflow('sorting');
	incr(sort_ptr);
	stat if sort_ptr>max_sort_ptr then max_sort_ptr←sort_ptr;@+tats
	if c=0 then depth[sort_ptr]←infinity else depth[sort_ptr]←d;
	head[sort_ptr]←bucket[collate[c]]; bucket[collate[c]]←0;
	end;
end;

@ @<Sort and output...@>=
sort_ptr←0; unbucket(1);
while sort_ptr>0 do
	begin cur_depth←cat[sort_ptr];
	if (link[head[sort_ptr]]=0)∨(cur_depth=infinity) then
		@<Output index entries for the list at |sort_ptr|@>
	else @<Split the list at |sort_ptr| into further lists@>;
	end

@ @<Split the list...@>=
begin next_name←head[sort_ptr];
repeat cur_name←next_name; next_name←link[cur_name];
	cur_byte←byte_start[cur_name]+cur_depth;
	if cur_byte=byte_start[cur_name+1] then c←0 {we hit the end of the name}
	else	begin c←byte_mem[cur_byte];
		if (c≤"Z")∧(c≥"A") then c←c+@'40;
		end;
	link[cur_name]←bucket[c]; bucket[c]←cur_name;
until next_name=0;
decr(sort_ptr); unbucket(cur_depth+1);
end

@ @<Output index...@>=
begin cur_name←head[sort_ptr];
debug if trouble_shooting then debug_help;@+gubed
repeat out2("\")("+");
	@<Output the name at |cur_name|@>;
	@<Output the cross-references at |cur_name|@>;
	cur_name←link[cur_name];
until cur_name=0;
decr(sort_ptr);
end

@ @<Output the name...@>=
case ilk[cur_name] of
normal: out2("\")("\");
roman: do_nothing;
typewriter: out2("\")(".");
othercases out2("\")("&")
endcases;
out_name(cur_name);

@ Section numbers that are to be underlined are enclosed in `\.{\\[$\ldotsm$]}'.

@<Output the cross-references...@>=
@<Invert the cross-reference list at |cur_name|, making |cur_xref| the head@>;
repeat out2(",")(" "); cur_val←num(cur_xref);
if cur_val<def_flag then out_val(cur_val)
else	begin out2("\")("["); out_val(cur_val-def_flag); out("]");
	end;
cur_xref←xlink(cur_xref);
until cur_xref=0;
out("."); ex_finish_line;

@ To reverse the order of the linked list of cross references, we need
two more variables that point to cross reference entries.

@<Glob...@>=
@!next_xref,@!this_xref:0..max_refs; {pointer variables for inverting a list}

@ List inversion is best thought of as popping elements off one stack and
pushing them onto another. In this case |cur_xref| will be the head of
the stack that we push things onto.

@<Invert the cross-reference list at |cur_name|, making |cur_xref| the head@>=
this_xref←xref[cur_name]; cur_xref←0;
repeat next_xref←xlink(this_xref); xlink(this_xref)←cur_xref;
cur_xref←this_xref; this_xref←next_xref;
until this_xref=0
@* Debugging.
The \PASCAL\ debugger with which \.{WEAVE} was developed allows breakpoints
to be set, and variables can be read and changed, but procedures cannot be
executed. Therefore a `|debug_help|' procedure has been inserted in the main
loops of each phase of the program; when |ddt| and |dd| are set to appropriate
values, symbolic printouts of various tables will appear.

The idea is to set a breakpoint inside the |debug_help| routine,
at the place of the asterisks below.
Then when |debug_help| is to be activated, set |trouble_shooting|
equal to |true|. After stopping at the breakpoint, the |debug_help|
routine will prompt you for values of |ddt| and |dd|, discontinuing
this when |ddt≤0|; thus you type $2n+1$ integers, ending with zero or
a negative number, after which you return to the breakpoint on zero
or exit the routine if |ddt<0|.

Another global variable, |debug_cycle|, can be used to skip silently
past calls on |debug_help|. If |debug_cycle>1|, the program stops
only every |debug_cycle| times |debug_help| is called; however,
any error stop will set |debug_cycle| to zero.

@<Globals...@>=
debug@!trouble_shooting:boolean; {is |debug_help| wanted?}
@!ddt:sixteen_bits; {operation code for the |debug_help| routine}
@!dd:sixteen_bits; {operand in procedures performed by |debug_help|}
@!debug_cycle:integer; {threshold for |debug_help| stopping}
@!debug_skipped:integer; {we have skipped this many |debug_help| calls}
gubed

@ @<Set init...@>=
debug trouble_shooting←true; debug_cycle←1; debug_skipped←0; tracing←false;
trouble_shooting←false; debug_cycle←99999; {TEMPORARY!}
gubed

@ @↑system dependencies@>

@d breakpoint=888 {place where a breakpoint is desirable}

@p debug procedure debug_help; {routine to display various things}
label breakpoint,exit;
var k:sixteen_bits; {index into various arrays}
begin incr(debug_skipped);
if debug_skipped<debug_cycle then return;
debug_skipped←0;
breakpoint:
@{@&'*****************************breakpoint*****************************'@&@}
loop	begin write(tty,'#'); read(tty,ddt);
	if ddt<0 then return
	else if ddt=0 then goto breakpoint;
	read(tty,dd);
	case ddt of
	1: print_id(dd);
	2: print_text(dd);
	3: for k←1 to dd do print(chr(buffer[k]));
	4: for k←1 to dd do print(chr(module[k]));
	5: for k←1 to out_ptr do print(chr(out_buf[k]));
	6: for k←1 to dd do 
		begin print_cat(cat[k]); print(' ');
		end;
	othercases print('?')
	endcases;
	end;
exit:end;
gubed
@* The main program.
Let's put it all together now: \.{WEAVE} starts and ends here.
@↑system dependencies@>

@p begin initialize;
@<Store all the reserved words@>;
@<Phase I:...@>;
@<Phase II:...@>;
@<Phase III:...@>;
end_of_WEAVE:
stat @<Print statistics about memory usage@>;
tats
{here files should be closed if the operating system requires it}
end.

@ @<Print statistics about memory usage@>=
ex_print_nl('Memory usage statistics: ',
	name_ptr:0,' names, ', xref_ptr:0,' cross references;');
ex_print_nl('parsing required ',max_scr_ptr:0,' scraps, ',max_txt_ptr:0,
	' texts, ',max_tok_ptr:0,' tokens, ', max_stack_ptr:0,' levels;');
ex_print_nl('sorting required ',max_sort_ptr:0, ' levels.')
@* Index.
If you have read and understood the code for Phase III above, you know what
is in this index and how it got here. All modules in which an identifier is
used are listed with that identifier, except that reserved words are
indexed only when they appear in format definitions, and the appearances
of identifiers in module names are not indexed. Underlined entries
correspond to where the identifier was declared.